当前位置:Gxlcms > 数据库问题 > 使用jdk中的java.sql包中的方法进行jdbc连接

使用jdk中的java.sql包中的方法进行jdbc连接

时间:2021-07-01 10:21:17 帮助过:43人阅读

package com.qls.mybatis.first; 2 3 import java.sql.Connection; 4 import java.sql.DriverManager; 5 import java.sql.PreparedStatement; 6 import java.sql.ResultSet; 7 import java.sql.SQLException; 8 9 public class CrudJDBCTest { 10 11 /** 12 * 使用原生态的jdbc进行数据库连接。 13 * @throws SQLException 14 */ 15 public static void main(String[] args) throws SQLException { 16 // TODO Auto-generated method stub 17 //Connection 接口,与特定数据库的连接。 18 Connection connection=null; 19 //预编译对象 20 PreparedStatement preparedStatement=null; 21 //结果集 22 ResultSet resultSet=null; 23 try { 24 //加载驱动:这里加载的是mysql驱动。mysql的驱动是:com.mysql.jdbc.Driver 25 Class.forName("com.mysql.jdbc.Driver"); 26 /** 27 * wms-elite本机测试版是连接的数据库名 28 * root:是用户名。 29 * a123456:是密码。 30 */ 31 connection=DriverManager.getConnection( 32 "jdbc:mysql://localhost:3306/wms-elite本机测试版?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true", 33 "root", "a123456"); 34 //获取PreparedStatement对象: 35 String sql="SELECT *from user where address=?"; 36 preparedStatement=connection.prepareStatement(sql); 37 //绑定参数: 38 preparedStatement.setString(1, "北京市"); 39 //执行查询,查询出结果。 40 resultSet=preparedStatement.executeQuery(); 41 while(resultSet.next()){ 42 System.out.println("用户名是:"+resultSet.getString("username")+"\n"+"性别是:"+resultSet.getString(4)); 43 } 44 } catch (Exception e) { 45 e.printStackTrace(); 46 }finally{ 47 /** 48 * 关闭数据库连接。 49 * 关闭的顺序是:ResultSet,PreparedStatement,Connection. 50 */ 51 if (resultSet!=null) { 52 53 resultSet.close();//关闭结果集 54 } 55 if (preparedStatement!=null) { 56 57 preparedStatement.close();//关闭预编译对象 58 } 59 if (connection!=null) { 60 61 connection.close();//关闭连接。 62 } 63 64 } 65 } 66 67 }/*output: 68 用户名是:张三 69 性别是:1 70 *///:~

上面的代码基本上对重要的语句都进行了注释。输出结果:

用户名是:张三
69 性别是:1
见下图所示:

技术分享

使用jdk中的java.sql包中的方法进行jdbc连接

标签:static   遍历   ace   code   分享   getc   rate   name   from   

人气教程排行