import java.sql.*;
import java.util.ResourceBundle;
public class JDBCTest01{
public static void main(String[] args){
//配置文件绑定
ResourceBundle bundle=ResourceBundle.getBundle("jdbc");
String driver=bundle.getString("driver");
String url=bundle.getString("url");
String user=bundle.getString("user");
String password=bundle.getString("password");
Connection connection=null;
Statement statement=null;
ResultSet rs=null;
try{
//注册驱动
Class.forName(driver);
//注册驱动第二种方法
//DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());
//获取连接
connection=DriverManager.getConnection(url,user,password);
//获取数据库操作对象
statement=connection.createStatement();
//执行mysql语句
String sql="update dept set dname='xiaoshou2',loc='天津2'where deptno=52";
int count=statement.executeUpdate(sql);//执行增删改insert delete update
System.out.println(count==1 ? "修改成功" : "修改失败");
String sql2="select empno as a,ename as b,sal as c from emp";
rs=statement.executeQuery(sql2);
//执行查询结果集
while (rs.next()){
String edetno=rs.getString("a");
String ename=rs.getString("b");
String sal=rs.getString("c");
System.out.println(edetno+","+ename+sal);
}
}catch(SQLException e){
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally{
if(rs!=null){
try{
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(statement!=null)
try{
statement.close();
}catch(SQLException e){
e.printStackTrace();
}
if(connection!=null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//释放资源
}
}
idea连接数据库
最新推荐文章于 2024-09-15 08:03:51 发布