Java连接示例
<p class="p">Java连接示例如下:</p>
<pre class="pre codeblock"><code>import java.sql.*;
import com.mysql.jdbc.Driver;
public class Demo {
public static void main(String[] args) throws SQLException, ClassNotFoundException{
String url = "jdbc:mysql://<域名>:<端口>/<Database>";
String user = "<username>";
String pwd= "<password>";
String driverName ="com.mysql.jdbc.Driver";
Connection conn = null;
String sql = "SELECT * FROM t";
try{
//加载驱动
Driver.class.forName(driverName);
//建立连接
conn = DriverManager.getConnection(URL,username,password);
//创建statement执行SQL语句
Statement ps = conn.createStatement();
//结果集处理
ResultSet rs = ps.executeQuery(sql);
while(rs.next()) {
System.out.println(rs.getString("id"));
}
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch(SQLException e){
e.printStackTrace();
}
//关闭连接
finally{
if(conn!=null){
try{
conn.close();
}catch(SQLException e){
e.printStackTrace();
}
}
}
}
}</code></pre>
提交成功!非常感谢您的反馈,我们会继续努力做到更好!