初入JDBC

来源:互联网 发布:淘宝晒图返现违规吗 编辑:程序博客网 时间:2024/06/07 03:00

/*

* #JDBC配置

* 1.注册驱动

* 2.获取连接connection

* 3.得到执行SQL语句的对象Statement

* 4.执行sql语句并返回结果

* 5.处理结果

* 6.关闭数据库

* */

/*

* ########

* 在进入jdbc之前需要加入mysql-connector-java-5.1.42.jar到工程中《jar下载地址https://dev.mysql.com/downloads/file/?id=470333》 两种加入方式

* 1.工程中新建文件夹并直接拖入其中, 然后右击jar ---> Build Path  ---->Add to Build Path

* 2.点击tileBar 中Project ---> Properties--->Java Build Path ----> Libraries--->Add external Jars

*/

/*

* 步骤1

* */

/*

* 通常不是用这中

* 原因

* 1.驱动会被注册两次

* 2.对jar有这强依赖性

*/  

// DriverManager.registerDriver(new com.mysql.jdbc.Driver());

/**

*使用反射注册使得对jar解偶和 

*/

Class.forName("com.mysql.jdbc.Driver");

/*

* 步骤2

* */

// Connection connect= DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb1", "root", "lgw123");

// Connection connect= DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb1?user=root&password=lgw123");

Properties info=new Properties();

info.setProperty("user","root");

info.setProperty("password","lgw123");

Connection connect= DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb1",info);

/*

* 步骤3

* */

Statement stmt = (Statement)connect.createStatement();

/*

* 步骤4

* */

// boolean isS=stmt.executeUpdate("");

ResultSet set= stmt.executeQuery("select *from user");

/*

* 步骤5

* */

while (set.next()) {

System.out.println(set.getObject(1));

System.out.println(set.getObject(2));

System.out.println(set.getObject(3));

System.out.println(set.getObject(4));

System.out.println(set.getObject(5));

System.out.println(set.getObject(6));

System.out.println(set.getObject(7));

System.out.println(set.getObject(8));

System.out.println("-----------------------");

}

/*

* 步骤6

* */

if (set!=null) {

try {

set.close();

} catch (SQLExceptione) {

//TODO Auto-generated catch block

e.printStackTrace();

}

}

if (stmt!=null) {

try {

stmt.close();

} catch (SQLExceptione) {

//TODO Auto-generated catch block

e.printStackTrace();

}

}

if (connect!=null) {

try {

connect.close();

} catch (SQLExceptione) {

//TODO Auto-generated catch block

e.printStackTrace();

}

}

0 0
原创粉丝点击