JDBC概述:
就是提供了使用java程序连接,操作数据库的一系列的API,不同的数据库厂只要根据各自的JDBC API提供各自的实现即可。 java 应用程序--->JDBC API -->JDBC 的驱动 --->数据库
2.获取数据库连接
//获取数据库的连接
public static Connection getConnection() throws Exception{
//1.获取数据库连接的基本信息
//1.1 创建 Properties 的对象,以流的形式,将配置文件中的基本信息读入程序
Properties info = new Properties();
info.load(new FileInputStream("jdbc.properties"));
//1.2 提供 4 个基本信息:url、driverClass、user、password
g password = info.getProperty("password");
//2.加载驱动
Class.forName(driverClass);
//3.使用 DriverManager 的 getConnection(url,user,password)方法
Connection conn = DriverManager.getConnection(url, user, password);
return conn;
}
public static void close(ResultSet rs,Statement st,Connection conn){
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(st != null){
try {
st.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
[jdbc.properties]
url=jdbc:mysql://127.0.0.1:3306/test
user=root
password=123456
driverClass=com.mysql.jdbc.Driver
#user=scott
#password=tiger
#url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
#driverClass=oracle.jdbc.driver.OracleDriver
3.Statement与ResultSet
3.1通过Connection对象的createStatement方法创建该对象
3.2该对象用于执行静态的sql语句,并且返回执行结果
3.3 Statement接口中定义下列方法用于执行SQL:ResultSet excuteQuery(String sql) , int excuteUpdate(String sql)