JDBC
Posted 云中之歌
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JDBC相关的知识,希望对你有一定的参考价值。
1 package db; 2 3 import java.io.FileInputStream; 4 import java.io.FileNotFoundException; 5 import java.io.IOException; 6 import java.sql.Connection; 7 import java.sql.DriverManager; 8 import java.sql.SQLException; 9 import java.util.Properties; 10 11 import javax.sql.rowset.JdbcRowSet; 12 import javax.sql.rowset.RowSetFactory; 13 import javax.sql.rowset.RowSetProvider; 14 15 16 public class RowSetFactoryTest { 17 private String driver; 18 private String url; 19 private String user; 20 private String pass; 21 public void initParam(String paramFile) throws FileNotFoundException, IOException, ClassNotFoundException { 22 //用Properties类加载属性文件 23 Properties prop = new Properties(); 24 prop.load(new FileInputStream(paramFile)); 25 driver = prop.getProperty("driver"); 26 url = prop.getProperty("url"); 27 user = prop.getProperty("user"); 28 pass = prop.getProperty("pass"); 29 Class.forName(driver); 30 } 31 32 public void update(String sql) throws SQLException { 33 RowSetFactory factory = RowSetProvider.newFactory(); 34 35 try ( 36 //使用RowSet的execute方式返回数据,则不再需DriverManager连接数据库了 37 //Connection conn = DriverManager.getConnection(url, user, pass); 38 /* 39 * for JDK1.6 40 * JdbcRowSet jdbcRs = new JdbcRowSetImpl(conn); 41 */ 42 // for JDK 1.7 43 JdbcRowSet jdbcRs = factory.createJdbcRowSet(); 44 ) { 45 jdbcRs.setUrl(url); 46 jdbcRs.setUsername(user); 47 jdbcRs.setPassword(pass); 48 jdbcRs.setCommand(sql); 49 jdbcRs.execute(); 50 51 jdbcRs.afterLast(); 52 //向前滚动结果集 53 while(jdbcRs.previous()) { 54 System.out.println(jdbcRs.getInt(1)+"\t"+jdbcRs.getString(2)+"\t"+jdbcRs.getString(3)); 55 56 if (jdbcRs.getInt("jdbc_id") == 3) { 57 //修改指定行记录,因为 JdbcRowSet 继承自 ResultSet, 所以修改记录的方式也一样 58 jdbcRs.updateString("jdbc_name", "小明"); 59 jdbcRs.updateRow(); 60 System.out.println("修改成功: "); 61 System.out.println(+jdbcRs.getInt(1)+"\t"+jdbcRs.getString(2)+"\t"+jdbcRs.getString(3)); 62 } 63 64 } 65 } 66 } 67 68 public static void main(String[] args) throws FileNotFoundException, ClassNotFoundException, IOException, SQLException { 69 RowSetFactoryTest jt = new RowSetFactoryTest(); 70 jt.initParam("mysql.ini"); 71 jt.update("select * from jdbc_test"); 72 } 73 }
以上是关于JDBC的主要内容,如果未能解决你的问题,请参考以下文章