内容:供程序员调用的接口与类,集成在java.sql和javax.sql包中,如:
DriverManager类
Connection接口
Statement接口
ResultSet接口
1.Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
2.Connection conn = DriverManager.getConnection("jdbc:sqlserver://127.0.0.1:1433;databasename=data", "sa", "123");
Statement stm=con.createStatement();
String sql="select * from users where username=‘"+name+"‘ and userpwd="+pwd;
ResultSet rs=stm.executeQuery(sql);
if(rs.next()){
System.out.println("成功");
}else{
System.out.println("不成功");
}
//得到连接Connection
public static Connection getConn(){
Connection conn = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");//加载驱动包
conn = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:orcl","scott","tiger");
//创建连接数据库的流
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
/*关闭连接的方法:先关结果集 再关船 再关连接
* 铁船继承普通船
*/
public static void closeConn(ResultSet rs,Statement st,Connection conn){
try {
if(rs!=null){
rs.close();
}
if(st!=null){
st.close();
}
if(conn!=null){
conn.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//1.加载驱动
Class.forName("oracle.jdbc.driver.OracleDriver");
//2.建连接
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger");
/*3.准备sql语句:
* 一次插入50条数据
*/
String sql = "insert into student values(seq_stu.nextval,?,?,?,to_date(?,‘yyyy-mm-dd‘),?)";
//4.创建铁船
PreparedStatement pst = conn.prepareStatement(sql);
for(int i=0;i<50;i++){
pst.setString(1, "小菜"+i);
pst.setString(2, "女");
pst.setDouble(3, 100.0);
pst.setString(4, "1900-1-1");
pst.setString(5,"马兰山马兰坡");
//把数据存入Batch容器
pst.addBatch();
}
int[] arr = pst.executeBatch();
///*5.执行sql语句并返回结果
if(arr.length>=50){
System.out.println("添加成功");
}
//6.关连接
pst.close();
conn.close();
System.out.println("程序结束");
事务:
public static void main(String[] args) throws Exception {
//1.加载驱动
Class.forName("oracle.jdbc.driver.OracleDriver");
//2.建连接
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger");
System.out.println(conn);
//开启事务:设置不自动提交
conn.setAutoCommit(false);
/*3.准备sql语句:
* 小强1的钱减少100
* 小强3的钱增加100
*/
String sql = "update student set stu_money=stu_money-100 where stu_id=23";
String sql2 = "update student set stu_money=stu_money+100 where stu_id=24";
//4.创建Statement;普通船
Statement st = conn.createStatement();
///*5.执行sql语句并返回结果
int a = st.executeUpdate(sql);
int b = st.executeUpdate(sql2);
if(a>0&&b>0){
//如果两个操作都成功了 提交事 务
conn.commit();
}else{
//回滚:恢复到原来的状态
conn.rollback();
}
//6.关连接
st.close();
conn.close();
System.out.println("程序结束");
}