import javax.xml.stream.events.Comment;
import java.sql.*;
public class TestMysqlJdbc {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//第一步,加载数据库驱动
Class.forName("com.mysql.cj.jdbc.Driver");
System.out.println("加载mysql数据库驱动成功");
//第二步,创建数据库链接
String mysqlStr = "jdbc:mysql://localhost:3307/java2012a?characterEncoding=utf-8";
String user = "root";
String password = "123456";
conn = DriverManager.getConnection(mysqlStr,user,password);
System.out.println("数据库链接已经创建");
//第三步,定义sql对象
// String sql = "drop table if exists student";
String sql = "select * from student";
//第四步,获取执行sql对象
stmt = conn.createStatement();
//第五步,执行sql语句
// int result = stmt.executeUpdate(sql);
ResultSet result = stmt.executeQuery(sql);
//第六步,处理从数据库返回的数据
System.out.println(result);
}catch (ClassNotFoundException | SQLException e){
e.printStackTrace();
}finally {
//第七步,关闭数据库的相关资源,一般写在finally里边
if (stmt != null) {
try {
stmt.close();
} catch (SQLException t) {
t.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException x ) {
x.printStackTrace();
}
}
}
}
}
注意:
String mysqlStr = "jdbc:mysql://localhost:3307/java2012a?characterEncoding=utf-8"; String user = "root"; String password = "123456";
这三行一定要看好,一个是是否是这个数据库,一个是用户名,一个是密码,一定要保证这三个全对,缺一不可。