Java连接数据库详细代码及注释

一:建立连接
public class DBConnection{
/ /1. 连接XX数据库的驱动管理
private statc final String driverManager=“com.mysql.jdbc.Driver” ;
/ /2. 建立连接:
private static Connection conn;//(conn为数据库连接的全局变量)
/ / 3.代理;操作数据库(负责增删改操作)
private static Statement stmt; (增删改)
/ /4.结果集:负责显示查询结果
private static ResultSet rs;
public static Connection getconn(){ / /建立连接的过程
String url=“jdbc: mysql://localhost:3306/shopdb”; //引号内容为将要访问的数据库地址
String uname=“root” ;//用户名
String pwd=“rootroot”; //密码
try{
class.forName(driverManager); //1.加载驱动
conn=(Connection)DriverManager.getConnection(url, uname, pwd);//2.获取链接
}catch(Exception e){
e.printStackTrace();
}
return conn;
}

二、根据sql语句实现数据库的增删改操作:
public static int update(String sql){ / /返回的是执行sql语句后影响的行数
//1.获取连接
cnn=getConn();
int line=0;
try{
stmt=conn.createStatement(); //创建代理
line=stmt.executeUpdate(sql); //用代理执行sql语句
}catch(SQLexception e){
e.printStackTrace();
}
return line;
}
三、根据sql语句实现查询操作:
private static ResultSet query(){ / /返回的是查询后的结果集
conn=getConn();//1.获取链接
rs=null; //结果集
try{
stmt=conn.createStatement();
rs=stmt.executeQuery(sql) ;
}catch(SQLexception e){
e.printStackTrace();
}
return rs;
}
//主方法实现:
public static void main(String[] args) {
实现数据库是否连接成功*****
conn=getConn();
if(connnull){
System.out.println(“连接失败!”);
}else{
System.out.println(“连接成功!”);
}
用sql语句实现增删改**************
int num=update(“INSERT INTOshopuser(user_name,user_sex,user_phone)VALUES(‘苏姗姗’,‘女’,‘13437218614’)”); //增加
int num=update(“delete from shopuser where user_name=‘林小娘’”);//删除
int num=update(“update shopuser set user_name=‘刘毛静’,user_sex=‘男’ where id=‘6’”); //修改
System.out.println(“总共影响”+num+“行!”);
用sql语句实现查询*************************
rs=query(“select *from shopuser”);
System.out.println(rs
null?“没有”:“有”);
try {
while(rs.next()){//结果集是否有下一个
System.out.print(“编号:”+rs.getInt(“id”));
System.out.print(“姓名:”+rs.getString(“user_name”));
System.out.print(“性别”+rs.getString(“user_sex”));
System.out.print(“电话”+rs.getString(“user_phone”));
System.out.println();
}
} catch (SQLException e) {
e.printStackTrace();
}
}

猜你喜欢

转载自blog.csdn.net/zhangpupu320/article/details/89056990