当前位置:Gxlcms > 数据库问题 > JDBC示例

JDBC示例

时间:2021-07-01 10:21:17 帮助过:4人阅读

package jdbc; 2 3 import java.sql.Connection; 4 import java.sql.DriverManager; 5 import java.sql.PreparedStatement; 6 import java.sql.ResultSet; 7 import java.sql.SQLException; 8 import java.sql.Statement; 9 10 11 public class JDBCTest { 12 13 public static void jdbcDemoSelect(String driver,String url,String user,String password) throws Exception { 14 15 //1.加载类驱动 16 Class.forName(driver); 17 Connection con = DriverManager.getConnection(url,user,password); 18 19 // if(!con.isClosed()) 20 // System.out.println("succeeded connection to the database"); 21 22 //2.创建statement类对象,用来执行SQL语句 23 Statement statement = con.createStatement(); 24 25 //SQL语句 26 String sql = "select * from emp"; 27 28 //3.ResultSet类,用来存放获取的结果集 29 ResultSet set = statement.executeQuery(sql); 30 31 String eid=null,ename=null,price=null; 32 33 while(set.next()) { 34 eid = set.getString("eid"); 35 ename = set.getString("ename"); 36 price = set.getString("price"); 37 38 System.out.println(eid+"\t"+ename+"\t"+price); 39 } 40 41 } 42 43 public static void jdbcDemoUpdate(String driver,String url,String user,String password) throws Exception { 44 45 //1.加载类驱动 46 Class.forName(driver); 47 Connection con = DriverManager.getConnection(url,user,password); 48 49 String sql = "update emp set price=? where eid=?"; 50 51 //2。传值调用方法 52 PreparedStatement ps = con.prepareStatement(sql); 53 ps.setDouble(1, 3.6); 54 ps.setDouble(2, 1101); 55 56 //执行结果 57 ps.executeUpdate(); 58 59 } 60 61 public static void jdbcDemoInsert(String driver,String url,String user,String password) throws Exception { 62 63 Class.forName(driver); 64 Connection con = DriverManager.getConnection(url,user,password); 65 66 String sql = "INSERT INTO emp VALUES(?,?,?)"; 67 68 PreparedStatement ps = con.prepareStatement(sql); 69 ps.setInt(1, 1108); 70 ps.setString(2, "牛奶"); 71 ps.setDouble(3, 3.0); 72 73 ps.executeUpdate(); 74 75 } 76 77 public static void jdbcDemoDelete(String driver,String url,String user,String password) throws Exception { 78 79 Class.forName(driver); 80 Connection con = DriverManager.getConnection(url,user,password); 81 82 String sql = "DELETE FROM emp WHERE eid=?"; 83 84 PreparedStatement ps = con.prepareStatement(sql); 85 ps.setInt(1, 1108); 86 87 ps.executeUpdate(); 88 89 } 90 91 public static void main(String[] args) throws Exception { 92 93 //驱动名 94 String driver = "com.mysql.jdbc.Driver"; 95 //url指向要访问的数据库my_DB 96 String url = "jdbc:mysql://localhost:3306/my_DB"; 97 //mysql用户名 98 String user = "root"; 99 //密码 100 String password = "123456"; 101 102 // jdbcDemoInsert(driver,url,user,password); 103 104 jdbcDemoDelete(driver,url,user,password); 105 106 } 107 108 }

 

JDBC示例

标签:var   ips   str   password   tst   ice   tab   create   package   

人气教程排行