package six_jdbc;
import java.sql.*;
public class Dbdemo {
public static void main(String[] args) {
ResultSet result = null;
Connection con = null;
Statement statement = null;
try {
//第一步:将想要连接的数据库驱动类加载到JVM中,加载过程中并向DriverManager注册Driver
//成功加载后,会将Mysql的驱动Driver类的实例注册到DriverManager类中。???
//使得线面我们获取Connection只需通过DriverManager就可以了。我不需要通过每个数据库具体的Driver.
Class.forName("com.mysql.jdbc.Driver").newInstance();
//第二步,通过DriverManager获取一个和mysql的连接实例
String JDBCUrl = "jdbc:mysql://localhost:3306/kgw?useUnicode=true&characterEncodeing=utf-8";
String username = "root";
String password = "123456";
//接受一个jdbcurl,username,password
con = DriverManager.getConnection(JDBCUrl,username,password);
//第三步通过con连接获取到Statement实例,执行sql语句
statement = con.createStatement();//statement实例是用于一些不带参数的sql执行,查询,更新,插入
//第四部步,statement执行sql语句,查询到的结果集到ResultSet实例,简单查询,唯有where语句的查询
result = statement.executeQuery("select * from emp");
//第五步:从结果集中获取数据
while (result.next()){
int id = result.getInt("id");
int username1 = result.getInt("username");
int pwd = result.getInt("pwd");
System.out.println(id+ "\t" + username1 + "" + pwd);
}
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally {
//第六步释放资源
//关闭JDBC对象 操作完成以后要把所有使用的JDBC对象全都关闭,
// 以释放JDBC资源,关闭顺序和声 明顺序相反: 1、关闭记录集 2、关闭声明 3、关闭连接对象
try {
if(result != null){
result.close();
}
if(statement != null){
statement.close();
}
if(con != null){
con.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
JDBC连接数据库核心六步(ps:看的别人的)
最新推荐文章于 2024-04-20 03:44:22 发布