通过JDBC连接MySQL
文章目录
Talk is cheap, just show the code.
{% codeblock lang:java %} import java.sql.*;
public class MySQLTest {
public static void main(String[] args) throws Exception {
// 驱动程序名
String driver = "com.mysql.jdbc.Driver";
// URL指向要访问的数据库名abc,useSSL=false使控制台不显示SSL警告
String url = "jdbc:mysql://127.0.0.1:3306/abc?useSSL=false";
// MySQL配置时的用户名
String user = "root";
// MySQL配置时的密码
String password = "123456";
// 变量提前声明
Connection conn = null;
Statement statement = null;
ResultSet rs = null;
// 要执行的SQL语句
String sql = "select * from mytable";
try {
// 加载驱动程序,加载失败会抛异常
Class.forName(driver);
// 连接数据库,连接失败也会抛异常
conn = DriverManager.getConnection(url, user, password);
if (!conn.isClosed())
System.out.println("Succeeded connecting to the Database!");
// statement用来执行SQL语句
statement = conn.createStatement();
// 结果集
rs = statement.executeQuery(sql);
while (rs.next()) {
// 输出结果,数据库abc很简单,只有一个table,里面两项分别是name和date
System.out.println(rs.getString(“name”) + "\t" + rs.getDate(“date”));
}
} catch (ClassNotFoundException e) {
System.out.println("Sorry,can`t find the Driver!");
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
// 再次try catch抓异常
try {
if (rs != null) {
rs.close();
}
if (statement != null) {
statement.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
throw e;
}
}
}
} {% endcodeblock %}