Idea的jdbc中的查询与增删该
在上一篇的折磨中 终于写好了代码
来总结一下其中的奥妙
(相同部分:)1、有mysql并且与主机建立连接 2、有jar包并且复制到自己创建的libs文件下,右键add
3、需要写main方法
4、需要写
Class.forName("com.mysql.jdbc.Driver");
来注册驱动
5、都需要
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql", "root", "root");
建立与数据库连接(如果报错找不到的话 可以看一下我上一篇踩坑记录,比较踩了一晚上)
(不同部分:)
-增加的语句中写的是返回的行数以及sql语句
Statement的executeUpdate方法;
String sql = "INSERT INTO db1(age,NAME,TIME) VALUE(28,\"tt\",NULL)";//直接从可视化复制过来比较正确 Statement stmt = conn.createStatement(); int i = stmt.executeUpdate(sql); System.out.println(i);
-查找的语句是返回查询结果以及写的是sql查询语句,用的是
Statement的executeQuery方法
String sql = "SELECT * FROM db1";//直接从可视化复制过来比较正确 Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql); System.out.println(rs); while (rs.next()){ int id = rs.getInt("id"); String name = rs.getString("name"); int age = rs.getInt("age"); Time time = rs.getTime("time"); System.out.println(id+" "+name+" "+age+" "+time); } rs.close();
*完整代码
package cn.it.com; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class JdbcInset { public static void main(String[] args) { try { Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql", "root", "root"); String sql = "INSERT INTO db1(age,NAME,TIME) VALUE(28,\"tt\",NULL)";//直接从可视化复制过来比较正确 Statement stmt = conn.createStatement(); int i = stmt.executeUpdate(sql); System.out.println(i); } catch (SQLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } }
package cn.it.com; import java.sql.*; public class JdbcFind { public static void main(String[] args) { try { Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql", "root", "root"); String sql = "SELECT * FROM db1";//直接从可视化复制过来比较正确 Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql); System.out.println(rs); while (rs.next()){ int id = rs.getInt("id"); String name = rs.getString("name"); int age = rs.getInt("age"); Time time = rs.getTime("time"); System.out.println(id+" "+name+" "+age+" "+time); } rs.close(); } catch (SQLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } }