package py.db.com;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import com.mysql.jdbc.PreparedStatement;
public class DB_update {
public static void main(String[] args) {
//TestUpdate();
TestUpdatePre();
}
private static void TestUpdatePre() {
// TODO Auto-generated method stub
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "uplooking";
String sql1 = "update emp set sal = sal + ? where empno = 7900";
String sql2 = "select ename from emp where hiredate<?";
String sql3 = "update emp set sal = sal + 120 where empno = 7900";
Connection conn = null;
java.sql.PreparedStatement ps = null;
try {
//注册并载入数据库驱动
Class.forName("com.mysql.jdbc.Driver");
System.out.println("数据库驱动加载成功...");
//建立数据库连接
conn = DriverManager.getConnection(url, user, password);
System.out.println("数据库连接已建立...");
//准备一个处理器用来包装sql代码
ps = conn.prepareStatement(sql1);
//设置参数
ps.setInt(1, 250);
//执行sql代码
int rs = ps.executeUpdate();
if (rs == 1) {
System.out.println("数据库sql执行成功.");
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("数据库驱动加载失败");
e.printStackTrace();
} catch (SQLException e) {
System.out.println("数据库通讯失败");
//e.printStackTrace();
} finally {
//关闭对象及连接
try {
ps.close();
conn.close();
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("对象关闭失败");
//e.printStackTrace();
}
}
}
private static void TestUpdate() {
// TODO Auto-generated method stub
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "uplooking";
String sql1 = "select ename,empno from emp where empno=? and sal>?";
String sql2 = "select ename from emp where hiredate<?";
String sql3 = "update emp set sal = sal + 120 where empno = 7900";
Connection conn = null;
Statement stmt = null;
try {
//注册并载入数据库驱动
Class.forName("com.mysql.jdbc.Driver");
System.out.println("数据库驱动加载成功...");
//建立数据库连接
conn = DriverManager.getConnection(url, user, password);
System.out.println("数据库连接已建立...");
//准备一个处理器用来包装sql代码
stmt = conn.createStatement();
//执行sql代码
int rs = stmt.executeUpdate(sql3);
if (rs == 1) {
System.out.println("数据库sql执行成功.");
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("数据库驱动加载失败");
e.printStackTrace();
} catch (SQLException e) {
System.out.println("数据库通讯失败");
//e.printStackTrace();
} finally {
//关闭对象及连接
try {
stmt.close();
conn.close();
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("对象关闭失败");
//e.printStackTrace();
}
}
}
}
本文出自 “影魔登场” 博客,请务必保留此出处http://woodywoodpecker.blog.51cto.com/4820467/1649730