(四十五)如何通过JDBC访问数据库
JDBC: Java DataBase Connectivity (java 数据库连接)
作用:用于在java程序中实现数据库操作功能,它提供了执行SQL语句、访问各种数据库的方法,并为各种不同的数据库提供了统一的操作接口。
(创建与数据库连接、发送SQL语句到数据库、处理数据并查询结果)
步骤:
①加载JDBC驱动器
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Test {
public static void main(String[] args)throws Exception {
String user="root";
String password="123456";
String url="jdbc:mysql://localhost:3306/learn";
String driver="com.mysql.jdbc.Driver";
Connection con=null;
Statement stmt=null;
ResultSet rs=null;
try {
//加载JDBC驱动,并将其注册到DriverManager中
Class.forName(driver);
//连接数据库,获得Connection对象
con=DriverManager.getConnection(url,user,password);
//建立Statement对象或PreparedStatement对象
stmt=con.createStatement();
//执行SQL
stmt.execute("insert into employee values(1,'jim1',25)");
stmt.execute("insert into employee values(2,'jim2',28)");
//访问结果集ResultSet对象
rs=stmt.executeQuery("select * from employee");
while(rs.next())
{
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getInt(3));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//关闭资源
try{
if(rs!=null) rs.close();
if(stmt!=null) stmt.close();
if(con!=null) con.close();
}catch(SQLException e)
{
System.out.println(e.getMessage());
}
}
}
}