今天学习IDEA操作JDBC,MySQL包导入到项目
// 1、注册数据库的驱动
// Driver driver=new com.mysql.jdbc.Driver();
// DriverManager.registerDriver(driver);
String driver = "com.mysql.jdbc.Driver";
Class.forName(driver);//java基础反射
// 2.获取数据库连接
String url = "jdbc:mysql://localhost:3306/fresh";
Connection connection = DriverManager.getConnection(url, "root", "");
//3.获取操作数据库的对象
Statement statement = connection.createStatement();
String sql = "select * from user";
ResultSet resultSet = statement.executeQuery(sql);
//4.遍历结果集,取出数据
while (resultSet.next()){
String name = resultSet.getString("name");
System.out.print("名字:"+name);
}
connection.close();
//更新数据
String sql = "UPDATE user set name='小萌' where id=1";
int resule = statement.executeUpdate(sql);
System.out.println(resule);
statement.close();
connection.close();
Junit单元测试
项目=》新建test目录 ,project structure=>选中test文件点击sources如此即可在test文件夹下创建java文件