1 package zuoye1; 2 3 import java.sql.DriverManager; 4 import java.sql.SQLException; 5 6 import com.mysql.jdbc.Connection; 7 import com.mysql.jdbc.ResultSet; 8 import com.mysql.jdbc.ResultSetMetaData; 9 import com.mysql.jdbc.Statement; 10 11 public class jdbc_connect { 12 13 /** 14 * @param args 15 */ 16 17 // 18 // CREATE DATABASE `mydb` /*!40100 DEFAULT CHARACTER SET utf8 */; 19 // CREATE TABLE `stuinfo` ( 20 // `ID` varchar(10) NOT NULL auto_increment, 21 // `NAME` varchar(30) DEFAULT NULL, 22 // `AGE` int(11) DEFAULT NULL, 23 // PRIMARY KEY (`ID`) 24 // ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 25 26 public static void main(String[] args) { 27 // TODO Auto-generated method stub 28 String user = "root" ; 29 String password = "a123456" ; 30 String url = "jdbc:mysql://localhost:3306/mydb" ; 31 String driver = "com.mysql.jdbc.Driver" ; 32 // String driver = "org.gjt.mm.mysql.Driver"; 33 String tableName = "stuinfo" ; 34 String sqlstr; 35 Connection con = null ; 36 Statement stmt = null ; 37 ResultSet rs = null ; 38 try { 39 Class.forName(driver); // 加載JDBC驅動。 40 con = (Connection) DriverManager.getConnection(url, user, password); // 連接數據庫 41 stmt = (Statement) con.createStatement(); 42 sqlstr = "insert into " + tableName 43 + " values ('20010838','honey',21)"; // 添加一條記錄。 44 stmt.executeUpdate(sqlstr); // 執行語句。 45 sqlstr = "select * from " + tableName; 46 rs = (ResultSet) stmt.executeQuery(sqlstr); 47 48 // 使用JDBC連接數據庫需要四步, 49 // 第一步加載驅動程序; 50 // 第二步,連接數據庫; 51 // 第三步,訪問數據庫; 52 // 第四步,執行查詢; 53 // 其中在第四步執行查詢時,要用statement類的executeQuery()方法來下達select指令以查詢數據庫, 54 // executeQuery()方法會把數據庫響應的查詢結果存放在ResultSet類對象中供我們使用。 55 // 即語句:String sql="select * from"+tableName; 56 // ResultSet rs=s.executeQuery(sql); 57 58 ResultSetMetaData rsmd = (ResultSetMetaData) rs.getMetaData(); 59 int j = 0 ; 60 j = rsmd.getColumnCount(); 61 for ( int k = 0; k < j; k++ ) { 62 System.out.print(rsmd.getCatalogName(k + 1)); // 獲得所在的Catalog名字 63 System.out.print("\t" ); 64 } 65 System.out.println(); 66 while (rs.next()) { 67 for ( int i = 0; i < j; i++ ) { 68 // 結果集ResultSet存有一個表,該表的當前行可以訪問。當前行的初始位置是null。 69 // 可以使用next方法移動到下一行,可以使用各種get方法從當前行獲取值。如getString(1)獲取第1列的數據。 70 System.out.print(rs.getString(i + 1 )); 71 System.out.print("\t" ); 72 } 73 System.out.println(); 74 } 75 } catch (ClassNotFoundException e1) { 76 System.out.println("數據庫驅動不存在!" ); 77 System.out.println(e1.toString()); 78 } catch (SQLException e2) { 79 System.out.println("數據庫存在異常!" ); 80 System.out.println(e2.toString()); 81 } finally { 82 try { 83 if (rs != null ) 84 rs.close(); 85 if (stmt != null ) 86 stmt.close(); 87 if (con != null ) 88 con.close(); 89 } catch (SQLException e) { 90 System.out.println(e.toString()); 91 } 92 } 93 } 94 95 }
?
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
