使用JDBC对数据库操作

1、导入Jar包

  mysql-connector-java-5.1.0-bin.jar

2、加载驱动

  Class.forName("com.mysql.jdbc.Driver");

3、建立连接

  Connection connection=null;

  connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/[数据库名字]","[用户名]","[密码]");

4、关闭连接

  if(rs!=null){rs.close();}

  if(pstmt!=null){pstmt.close();}

  if(connection!=null){connection.close();}

5、DEMO

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JdbcDemo {
public static void main(String[] args) {
Connection connection=null;
PreparedStatement pstmt=null;
ResultSet rs=null;
//加载驱动
try {
  Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
  e.printStackTrace();
}
//建立连接
try {
  connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/user?useUnicode=true&characterEncoding=utf-8","root","qwq123");
  //查询
  String sql_select="SELECT id,name,phone FROM stu";
  pstmt=connection.prepareStatement(sql_select);
  rs=pstmt.executeQuery();
  System.out.println("序号\t编号\t姓名\t电话");
  for (int i=1;rs.next();i++) {
    System.out.println(i+"\t"+rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getString(3));
  }
  //增加
  String sql_insert="INSERT INTO stu(`name`,phone) VALUES(?,?)";
  pstmt=connection.prepareStatement(sql_insert);
  pstmt.setString(1, "Peter");
  pstmt.setString(2, "13122223333");
  int result1=pstmt.executeUpdate();
  if (result1>0) {
    System.out.println("添加成功~!");
  }
  //删除
  String sql_delete="DELETE FROM stu WHERE id = ?";
  pstmt=connection.prepareStatement(sql_delete);
  pstmt.setInt(1, 1);
  int result2=pstmt.executeUpdate();
  if (result2>0) {
  System.out.println("删除成功~!");
  }
  //修改
  String sql_update="UPDATE stu set `name`=? WHERE id=?";
  pstmt=connection.prepareStatement(sql_update);
  pstmt.setString(1, "Anna");
  pstmt.setInt(2, 21);
  int result3=pstmt.executeUpdate();
  if (result3>0) {
    System.out.println("修改成功~!");
  }
} catch (SQLException e) {
  e.printStackTrace();
}finally {
  //关闭连接
try {
  if (rs!=null) {rs.close();}
  if (pstmt!=null) {pstmt.close();}
  if (connection!=null) {connection.close();}
} catch (SQLException e) {
  e.printStackTrace();
}
}
}
}

posted @ 2019-11-18 01:08  Annuush  阅读(157)  评论(0编辑  收藏  举报