import java.sql.*;
import com.mysql.jdbc.exceptions.*;
public class lab1 {
public static void main(String[] args) {
//定义字符串、连接、语句、结果集
String url="jdbc:mysql://localhost:3306/jdbc";
String username="root";
String password="123456";
String dirver="com.mysql.jdbc.Driver";
Connection con=null;
Statement stmt=null;
ResultSet rs=null;
try{
//加载驱动
Class.forName(dirver);
//建立连接
con=DriverManager.getConnection(url,username,password);
//创建数据库操作对象
stmt=con.createStatement();
String sql1="insert into member values(1005,'xiangguo','19800202','28','888888')";//插入数据
String sql2="insert into member values(1006,'lining','19800203','26','888888')";
//操作数据库 处理结果
int count=0;
try{
count=stmt.executeUpdate(sql1);
}catch(MySQLIntegrityConstraintViolationException e){
System.out.println("主键不允许重复!");
}
count=stmt.executeUpdate(sql2);
count=stmt.executeUpdate("update member set age=age+1");
System.out.println("恭喜你,成功插入了"+count+"条记录!");
System.out.println("恭喜你,成功更新了"+count+"条记录!");
String sql="select * from member";
rs=stmt.executeQuery(sql);
System.out.println("******************************");
System.out.println("会员ID/t姓名/t密码/t/t年龄/tOICQ号");
while(rs.next()){ //从结果集中获取每个列中的值
int id=rs.getInt(1); //获取当前记录中第1列内容
String userName=rs.getString(2);//获取当前记录中第2列内容
String passWord=rs.getString(3);//获取当前记录中第3列内容
int age=rs.getInt(4); //获取当前记录中第4列内容
String oicq=rs.getString(5); //获取当前记录中第5列内容
System.out.println(id+"/t"+userName+"/t"+passWord+"/t"+age+"/t"+oicq);
}
}catch(ClassNotFoundException e){
e.printStackTrace();
}catch(MySQLSyntaxErrorException e){
System.out.println("不存在的数据库");
e.printStackTrace();
}
catch(SQLException e){
e.printStackTrace();
}finally{
try{
if(rs!=null)rs.close(); //关闭结果集
}catch(Exception ee){
ee.printStackTrace();
}
try{
if(stmt!=null)stmt.close();//关闭编译语句
}catch(Exception ee){
ee.printStackTrace();
}
try{
if(con!=null)con.close();//关闭数据库连接
}catch(Exception ee){
ee.printStackTrace();
}
}
}
}