本次使用的数据库为:
import java.sql.*;
public class test2 {
//数据库的用户名与密码
static final String JDBC_Driver = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/test1";
//数据库的用户名与密码
static final String USER = "root";
static final String PASS = "";
public static void fetchData(Connection con) {//读取数据
try {
Statement stm = con.createStatement();
String sql = "select * from emp";
ResultSet re = stm.executeQuery(sql);
while(re.next()) {
String ename = re.getString("ename");
String hiredata = re.getString("hiredata");
String sal = re.getString("sal");
int deptno = re.getInt("deptno");
System.out.print("姓名: " + ename);
System.out.print(", 时间: " + hiredata);
System.out.print(", 工资: " + sal);
System.out.print(", 部门: " + deptno);
System.out.print("\n");
}
re.close();
}catch(SQLException se) {
se.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}finally {
System.out.println("MySQL数据库成功读取数据!" + "\n");
}
}
//插入数据
public static void insertData(Connection con) {
try {
String sql = "insert into emp (ename,hiredata,sal,deptno) values(?,?,?,?)";
PreparedStatement pst = con.prepareStatement(sql);
pst.setString(1, "Alan");
pst.setString(2, "2019-06-03");
pst.setString(3, "5012.3");
pst.setInt(4, 3);
pst.executeUpdate();
pst.close();
}catch(SQLException se) {
se.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}finally {
System.out.println("MySQL数据库数据插入成功!" + "\n");
}
}
public static void upData(Connection con) {//修改数据
try {
String sql = "update emp set deptno = ? where ename = ?";
PreparedStatement pst = con.prepareStatement(sql);
pst.setInt(1, 2);
pst.setString(2, "Tony");
pst.executeUpdate();
pst.close();
}catch(SQLException se) {
se.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}finally {
System.out.println("MySQL数据库成功修改数据!" + "\n");
}
}
public static void deleteData(Connection con) {//删除数据
try {
String sql = "delete from emp where deptno = ?";
PreparedStatement pst = con.prepareStatement(sql);
pst.setInt(1, 3);
pst.executeUpdate();
pst.close();
}catch(SQLException se) {
se.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}finally {
System.out.println("MySQL数据库成功删除数据!" + "\n");
}
}
public static void main(String args[]) {
Connection con = null;
Statement stmt = null;
ResultSet re= null;
try {
Class.forName("com.mysql.jdbc.Driver");//注册JDBC驱动
con = DriverManager.getConnection(DB_URL, USER, PASS);//利用信息链接数据库
stmt = con.createStatement();
if(! con.isClosed()) {
System.out.println("与数据库成功建立连接!");
}
fetchData(con);
insertData(con);
upData(con);
deleteData(con);
con.close();
}catch(SQLException se) {
se.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}finally {
System.out.println("执行结束!");
}
}
}