Jdbc连接数据库基本步骤
Jdbc连接数据库的基本步骤:
1 package demo.jdbc; 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 public class JdbcConn { 10 /** 11 *JDBC (Java Data Base Connectivity) 数据库连接,有以下几个步骤: 12 *1.加载驱动程序 Class.forName(driver); 13 *2.创建连接对象 Connection con = DriverManager.getConnection(url,username,password); 14 *3.创建sql语句的执行对象 15 *4.执行sql语句 16 *5.对执行结果进行处理 17 *6.关闭相关连接对象 (顺序跟声明的顺序相反)。 18 */ 19 public static void main(String[] args) { 20 String mysqlDriver = "com.mysql.jdbc.Driver"; 21 String mysqlUrl = "jdbc:mysql://localhost:3306/mybase"; 22 String mysqlUser = "root"; 23 String mysqlPass = "111"; 24 25 String oracleDriver = "oracle.jdbc.driver.OracleDriver"; 26 String oracleUrl = "jdbc:oracle:thin:@localhost:1521:XE"; 27 String userName = "zl"; 28 String passWord = "444"; 29 String sql = "select ename from emp"; 30 31 try { 32 Class.forName(oracleDriver); 33 } catch (ClassNotFoundException e) { 34 System.out.println("找不到驱动"); 35 e.printStackTrace(); 36 } 37 Connection conn = null; 38 try { 39 conn = DriverManager.getConnection(oracleUrl, userName,passWord ); 40 } catch (SQLException e) { 41 System.out.println("数据库连接错误"); 42 e.printStackTrace(); 43 } 44 Statement st = null; 45 try { 46 st = conn.createStatement(); 47 } catch (SQLException e) { 48 System.out.println("创建数据库声明类错误"); 49 e.printStackTrace(); 50 } 51 boolean flag = false; 52 int rows = 0; 53 ResultSet rs = null; 54 try { 55 flag = st.execute(sql); 56 rows = st.executeUpdate(sql); 57 rs = st.executeQuery(sql); 58 while(rs.next()){ 59 //通过列的标号来查询数据; 60 String name =rs.getString(1); 61 //通过列名来查询数据 62 String name2 = rs.getString("ename"); 63 System.out.println(name); 64 } 65 } catch (SQLException e) { 66 System.out.println("测试--"); 67 e.printStackTrace(); 68 } 69 //关闭数据连接对象 70 try { 71 if(rs!= null){ 72 rs.close(); 73 } 74 if(st!= null){ 75 st.close(); 76 } 77 if(conn!=null){ 78 conn.close(); 79 } 80 } catch (SQLException e) { 81 e.printStackTrace(); 82 } 83 } 84 }
每一个不曾起舞的日子,都是对生命的辜负。