时间:2021-07-01 10:21:17 帮助过:19人阅读
package org.cjit.io.student; /** * java实现MySQl的JDBC连接的七步 */ import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JdbcTest { * @p
package org.cjit.io.student;
/**
* java实现MySQl的JDBC连接的七步
*/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcTest {
* @param args
*/
private static Connection con;
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
//1.载入JDBC驱动程序包
Class.forName("com.mysql.jdbc.Driver");
//2.定义连接URL
String url = "jdbc:mysql://localhost:3306/test?user=root&password=root";
//3.建立连接
con = DriverManager.getConnection(url);
//4.创建Statement对象
Statement stmt = con.createStatement();
//5.执行查询操作
String query = "select*from person";
ResultSet rs = stmt.executeQuery(query);
//6.对查询结果进行处理
while (rs.next()) {
String name=rs.getString("姓名");
String password=rs.getString("密码");
System.out.println(rs.getString(2));
System.out.println(name+":"+password);
}
} catch (ClassNotFoundException e) {// 由16行抛出
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {// 由con,stmt抛出
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//7.关闭连接
if(con!=null){
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
System.exit(0);
}
}
}
}
}