JAVA对MySQL数据库的操作
一、导包:
使用JDBC连接MySQL数据库时,首先需要导入一个第三方的JAR包(点击下载),下载解压得到一个JAR包,并导入到JAVA项目中,如下图:
二、DBHelper类:
代码如下:
1 import java.sql.Connection; 2 import java.sql.DriverManager; 3 import java.sql.PreparedStatement; 4 import java.sql.SQLException; 5 6 public class DBHelper { 7 public static final String url = "jdbc:mysql://localhost/test"; 8 public static final String name = "com.mysql.jdbc.Driver"; 9 public static final String user = "root"; 10 public static final String password = "123456"; 11 12 public Connection conn = null; 13 public PreparedStatement pst = null; 14 15 public DBHelper(String sql) { 16 try { 17 Class.forName(name);// 指定连接类型 18 conn = DriverManager.getConnection(url, user, password);// 获取连接 19 pst = conn.prepareStatement(sql);// 准备执行语句 20 } catch (Exception e) { 21 e.printStackTrace(); 22 } 23 } 24 25 public void close() { 26 try { 27 this.conn.close(); 28 this.pst.close(); 29 } catch (SQLException e) { 30 e.printStackTrace(); 31 } 32 } 33 }
三、查询数据:
代码如下:
1 import java.sql.ResultSet; 2 import java.sql.SQLException; 3 4 public class Test { 5 private static String sql = null; 6 private static DBHelper helper = null; 7 private static ResultSet rs = null; 8 9 public static void main(String[] args) { 10 sql = "select empno,ename from emp"; 11 helper = new DBHelper(sql); 12 13 try { 14 rs = helper.pst.executeQuery(); 15 while (rs.next()) { 16 String empno = rs.getString(1); 17 String ename = rs.getString(2); 18 System.out.println(empno + "\t" + ename + "\t"); 19 } 20 rs.close(); 21 helper.close(); 22 } catch (SQLException e) { 23 e.printStackTrace(); 24 } 25 } 26 }
结果如下:
四、更新数据:
代码如下:
1 import java.sql.SQLException; 2 3 public class TestUpdate { 4 private static String sql = null; 5 private static DBHelper helper = null; 6 7 public static void main(String[] args) { 8 sql = "delete from emp where empno=1111"; 9 helper = new DBHelper(sql); 10 11 try { 12 int i = helper.pst.executeUpdate(); 13 if (i != 0) { 14 System.out.println("删除成功"); 15 } else { 16 System.out.println("删除失败"); 17 } 18 } catch (SQLException e) { 19 e.printStackTrace(); 20 } 21 } 22 }