Java Connection database, java Database
1 package com. shsxt. jdbcs; 2 3 import java. SQL. connection; 4 import java. SQL. driverManager; 5 import java. SQL. resultSet; 6 import java. SQL. SQLException; 7 import java. SQL. statement; 8 9/* 10 * jdbc steps: java Connection database 11 * // import jar package 12*1. Implementation class provided by the loading driver database vendor 13*2. Obtain the connection url username and password 14*3. Create a processing block send SQL statements to the server (database) prepare an SQL statement 15*4, result set 16*5, analysis result set 17*6, release the resource first, and then open 18 */19 public class Demo002JDBCConnect {20 public static void main (String [] args) throws ClassNotFoundException {21 Class. forName ("oracle. jdbc. driver. oracleDriver "); 22 String url =" jdbc: oracle: thin: @ localhost: 1521: orcl "; 23 String user =" scott "; 24 String pwd =" tiger "; 25 Connection conn = null; 26 Statement s = null; 27 ResultSet rs = null; 28 29 try {30 conn = DriverManager. getConnection (url, user, pwd); 31 s = conn. createStatement (); 32 S Tring SQL = "select deptno, dname, loc from dept"; 33 rs = s.exe cuteQuery (SQL); 34 while (rs. next () {35 int deptno = rs. getInt (1); // obtain the value 36 String dname = rs Based on the column number. getString ("dname"); // obtain the value 37 String loc = rs Based on the column name. getString (3); 38 System. out. println (deptno + "\ t" + dname + "\ t" + loc); 39} 40 41 42} catch (SQLException e) {43 e. printStackTrace (); 44} finally {45 if (rs! = Null) {46 try {47 rs. close (); 48} catch (SQLException e) {49 // TODO Auto-generated catch block50 e. printStackTrace (); 51} 52} 53 54 if (s! = Null) {55 try {56 s. close (); 57} catch (SQLException e) {58 // TODO Auto-generated catch block59 e. printStackTrace (); 60} 61} 62 63 if (conn! = Null) {64 try {65 conn. close (); 66} catch (SQLException e) {67 // TODO Auto-generated catch block68 e. printStackTrace (); 69} 70} 71 72} 73 74 75} 76}