赞
踩
2.测试驱动有没有添加成功
- try{
-
- Class.forName("com.mysql.cj.jdbc.Driver");
-
- out.println("驱动添加成功,可以进行数据库连接了");
-
- }catch (Exception e){
-
- out.println("驱动加载失败,错误原因是:"+e.getMessage());
-
- return;
-
- }
3.创建连接对象(usename是你的mysql上你设置的名字,默认为root,password是你对mysql连接时设置的密码)
Connection conn= DriverManager.getConnection(url,username,password);
其中url有以下几种写法,其中localhost和127.0.0.1表示IP,3306表示mysql的端口号,user表示连接的数据库
String url="jdbc:mysql://localhost:3306/user";
String url="jdbc:mysql://127.0.0.1:3306/user";
如何查看mysql的端口号呢?
4.写sql语句
String sql="select * from userinfo";
5.获取执行sql的对象Statement(本人觉得和python里面的游标作用有点相似)
Statement stm=conn.createStatement();
6.执行sql语句,不同sql语句有不同的execute方法,这里就不展示了
7.释放资源(关闭对象)
- stm.close();
- conn.close();
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。