一,jdbc 操作数据库
1,主要步骤:
加载驱动类 -> 获取数据库连接 -> 获取PreparedStatement ->执行数据库操作
2,实例
package jdbctest;
import java.sql.*;
import java.util.Iterator;
import java.util.List;
/**
* Created by Administrator on 2016/9/11.
* jdbc 操作数据库
*/
public class JdbcTest {
public static void main(String[] args) {
JdbcTest jdbcTest = new JdbcTest();
jdbcTest.updateTest();
// jdbcTest.queryTest();
}
/**
* jdbc添加测试
*/
public void updateTest(){
Connection con = null;
PreparedStatement pst = null;
String sql = "update t_student set name = ? where id = '43105'";
try {
con = JdbcUtil.getConnection();
con.setAutoCommit(false); //设置自动提交为false
pst = con.prepareStatement(sql); //获取
pst.setString(1, "name_6_2");
int i = pst.executeUpdate(); //执行查询
System.out.println("更新结果: " + i);
con.commit(); //提交
} catch (SQLException e){
try {
con.rollback(); //回滚
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
} finally { //关闭连接
try {
con.setAutoCommit(true);
pst.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* jdbc查询测试
*/
public void queryTest(){
Connection con = null;
PreparedStatement pst = null;
String sql = "select * from t_student limit 10";
ResultSet rs = null;
try {
con = JdbcUtil.getConnection();
pst = con.prepareStatement(sql); //获取
rs = pst.executeQuery(); //执行查询
while(rs.next()){ //遍历查询结果
System.out.println("1: " + rs.getInt("id") + ", 2: " + rs.getInt("age"));
}
} catch (SQLException e){
e.printStackTrace();
} finally { //关闭连接
try {
rs.close();
pst.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
-----------------------------------
package jdbctest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* Created by Administrator on 2016/9/11.
*/
public class JdbcUtil {
/*加载驱动类*/
static{
try {
Class.forName("com.mysql.jdbc.Driver"); //加载驱动类
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/*获取数据库连接*/
public static Connection getConnection(){
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/ssh", "root", ""); //获取连接
return con;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}
二,数据库连接池
1,作用
。。。。。。