JDBC初探
Posted Jason杰
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JDBC初探相关的知识,希望对你有一定的参考价值。
下载好JDBC之后,首先做的应该是查看它的文档
打开connector-j.html
1 import java.sql.Connection; 2 import java.sql.DriverManager; 3 import java.sql.SQLException; 4 5 // Notice, do not import com.mysql.jdbc.* 6 // or you will have problems! 7 8 public class LoadDriver { 9 public static void main(String[] args) { 10 try { 11 // The newInstance() call is a work around for some 12 // broken Java implementations 13 14 Class.forName("com.mysql.jdbc.Driver").newInstance(); 15 } catch (Exception ex) { 16 // handle the error 17 } 18 } 19 }
这是注册MySQL Connector/J,之后
1 import java.sql.Connection; 2 import java.sql.DriverManager; 3 import java.sql.SQLException; 4 5 Connection conn = null; 6 ... 7 try { 8 conn = 9 DriverManager.getConnection("jdbc:mysql://localhost/test?" + 10 "user=minty&password=greatsqldb"); 11 12 // Do something with the Connection 13 14 ... 15 } catch (SQLException ex) { 16 // handle any errors 17 System.out.println("SQLException: " + ex.getMessage()); 18 System.out.println("SQLState: " + ex.getSQLState()); 19 System.out.println("VendorError: " + ex.getErrorCode()); 20 }
连接数据库,之后Using JDBC Statement
Objects to Execute SQL
1 import java.sql.Connection; 2 import java.sql.DriverManager; 3 import java.sql.SQLException; 4 import java.sql.Statement; 5 import java.sql.ResultSet; 6 7 // assume that conn is an already created JDBC connection (see previous examples) 8 9 Statement stmt = null; 10 ResultSet rs = null; 11 12 try { 13 stmt = conn.createStatement(); 14 rs = stmt.executeQuery("SELECT foo FROM bar"); 15 16 // or alternatively, if you don‘t know ahead of time that 17 // the query will be a SELECT... 18 19 if (stmt.execute("SELECT foo FROM bar")) { 20 rs = stmt.getResultSet(); 21 } 22 23 // Now do something with the ResultSet .... 24 } 25 catch (SQLException ex){ 26 // handle any errors 27 System.out.println("SQLException: " + ex.getMessage()); 28 System.out.println("SQLState: " + ex.getSQLState()); 29 System.out.println("VendorError: " + ex.getErrorCode()); 30 } 31 finally { 32 // it is a good idea to release 33 // resources in a finally{} block 34 // in reverse-order of their creation 35 // if they are no-longer needed 36 37 if (rs != null) { 38 try { 39 rs.close(); 40 } catch (SQLException sqlEx) { } // ignore 41 42 rs = null; 43 } 44 45 if (stmt != null) { 46 try { 47 stmt.close(); 48 } catch (SQLException sqlEx) { } // ignore 49 50 stmt = null; 51 } 52 }
至此,就可以完成数据库的基本操作了
以上是关于JDBC初探的主要内容,如果未能解决你的问题,请参考以下文章
Java学习笔记8.1.1 初探JDBC - JDBC接口与类
Java学习笔记8.1.1 初探JDBC - JDBC接口与类
Java学习笔记8.1.2 初探JDBC - JDBC编程步骤
Java学习笔记8.1.2 初探JDBC - JDBC编程步骤
关于mysql驱动版本报错解决,Cause: com.mysql.jdbc.exceptions.jdbc4Unknown system variable ‘query_cache_size(代码片段