MySQL数据库的CRUD操作

import java.sql.Statement;


public class InsertDemo {
// 定义MySQL的数据库驱动程序
public static final String DBDRIVER = "org.gjt.mm.mysql.Driver" ;
// 定义MySQL数据库的连接地址
public static final String DBURL = "jdbc:mysql://localhost:3306/mldn" ;
// MySQL数据库的连接用户名
public static final String DBUSER = "root" ;
// MySQL数据库的连接密码
public static final String DBPASS = "admin" ;

public static void main(String[] args) {
// TODO Auto-generated method stub

Connection conn = null ; // 数据库连接
Statement stmt = null ; // 数据库操作
ResultSet rs = null ; // 保存查询结果
try {
Class.forName(DBDRIVER) ; // 加载驱动程序

//添加
String sql = "INSERT INTO user(name,password,age,sex,birthday) "+
" VALUES ('李兴华','www.mldn.cn',30,'男','2008-08-27')" ;

//修改
int id = 7 ;
String name = "李华" ; // 姓名
String password = "mldn" ; // 密码
int age = 25 ; // 年龄
String sex = "男" ; // 性别
String birthday = "1999-09-13" ;
String sql1 = "UPDATE user SET name='"+name+"',password='"
+password+"' , age=" + age + ",sex='"+sex+"',birthday='"
+birthday+"' WHERE id="+id  ;

//删除
String sql2 = "DELETE FROM user WHERE id="+id  ;

//查询
conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS) ;
stmt = conn.createStatement() ;
String sql3 = "SELECT id,name,password,age,sex,birthday FROM user" ;
stmt = conn.createStatement() ;
rs = stmt.executeQuery(sql3) ;
while(rs.next()){ // 依次取出数据
int id1 = rs.getInt(1) ; // 取出id列的内容
String name1 = rs.getString(2) ; // 取出name列的内容
String password1 = rs.getString(3) ; // 取出password列的内容
int age1 = rs.getInt(4) ; // 取出age列的内容
String sex1 = rs.getString(5) ; // 取出sex列的内容
java.util.Date d = rs.getDate(6) ; // 取出birthday列的内容
System.out.print("编号:" + id1 + ";") ;
System.out.print("姓名:" + name1 + ";") ;
System.out.print("密码:" + password1 + ";") ;
System.out.print("年龄:" + age1 + ";") ;
System.out.print("性别:" + sex1 + ";") ;
System.out.println("生日:" + d + ";") ;
System.out.println("-----------------------") ;
}
rs.close() ;
conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS) ;
stmt = conn.createStatement() ; // 实例化Statement对象
stmt.executeUpdate(sql) ; // 执行数据库更新操作
stmt.executeUpdate(sql1) ; // 执行数据库更新操作
stmt.executeUpdate(sql2) ; // 执行数据库更新操作
stmt.close() ; // 关闭操作
conn.close() ; // 数据库关闭
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值