MySQL第四天

配置文件:

url=jdbc:mysql:///girl
user=root
password=root
driver=com.mysql.jdbc.Driver
工具类:
private static String url;
private static String user;
private static String password;
private static String driver;
//文件的读取 读取一次拿到所有值 使用静态代码块
static {
try {
//读取资源文件 获取值 创建Properties集合类
Properties pro = new Properties();
//获取类加载器
ClassLoader classLoader = JDBCUtils.class.getClassLoader();
URL res = classLoader.getResource("jdbc.properties");
String path=res.getPath();
pro.load(new FileReader(path));
url=pro.getProperty("url");
user=pro.getProperty("user");
password=pro.getProperty("password");
driver=pro.getProperty("driver");

}catch (Exception e){
e.printStackTrace();
}
}
//获取连接对象
public static Connection getConnection() throws Exception{
return DriverManager.getConnection(url,user,password);
}
//释放资源
public static void close(Connection con, Statement stat){
if (stat!=null){
try {
stat.close();
}catch (Exception e){
e.printStackTrace();
}
}
if (con!=null){
try {
con.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
//释放资源
public static void close(Connection con, Statement stat, ResultSet rs){
if (rs!=null){
try {
rs.close();
}catch (Exception e){
e.printStackTrace();
}
}
if (stat!=null){
try {
stat.close();
}catch (Exception e){
e.printStackTrace();
}
}
if (con!=null){
try {
con.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
转账小功能:
public static void main(String[] args) {
Connection con = null;
PreparedStatement ps = null;
//1.获取连接
try {
con= JDBCUtils.getConnection();
//2.开启事务
con.setAutoCommit(false);
//3.获取执行sql对象
ps=con.prepareStatement("UPDATE yang set salary = salary+? where id=? ");
//4.使用PreparedStatement两次更新操作
ps.setDouble(1,500);
ps.setInt(2,1002);
ps.executeUpdate();
ps=con.prepareStatement("update yang set salary = salary-? where id=?");
ps.setDouble(1,100);
ps.setInt(2,1003);
ps.executeUpdate();
//5.提交事务
con.commit();
System.out.println("转账成功");
} catch (Exception e){
try {
con.rollback();
}catch (Exception e1){
e1.printStackTrace();
}
System.out.println("转账失败");
e.printStackTrace();
}finally {
//关闭资源
JDBCUtils.close(con,ps);
}
}
登陆程序:
public static void main(String[] args) throws Exception {
//从控制台输入用户名和密码
Scanner sc = new Scanner(System.in);
System.out.println("请输入用户名");
String name = sc.nextLine();
System.out.println("请输入密码");
String password = sc.nextLine();
login(name,password);
}
public static void login(String name,String password) throws Exception{
Connection con = JDBCUtils.getConnection();
//1.编写sql 未知内容使用?占位符
String sql = "select*from yang where ename=? and mgr=?";
//2.获得PreparedStatemnet对象
PreparedStatement ps = con.prepareStatement(sql);
//3.获得实际的参数
ps.setString(1,name);
ps.setString(2,password);
//4.执行sql语句
ResultSet rs = ps.executeQuery();
if (rs.next()){
System.out.println("登陆成功");
}else {
System.out.println("登陆失败");
}
//5.关闭资源
JDBCUtils.close(con,ps, rs);
}
 
 
 
posted @ 2019-04-08 20:23  顾与南歌`  阅读(152)  评论(0编辑  收藏  举报