Jdbc连接数据库基本步骤详解
Jdbc连接数据库的基本步骤,供大家参考,具体内容如下
package demo.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JdbcConn { /** *JDBC (Java Data Base Connectivity) 数据库连接,有以下几个步骤: *1.加载驱动程序 Class.forName(driver); *2.创建连接对象 Connection con = DriverManager.getConnection(url,username,password); *3.创建sql语句的执行对象 *4.执行sql语句 *5.对执行结果进行处理 *6.关闭相关连接对象 (顺序跟声明的顺序相反)。 */ public static void main(String[] args) { String mysqlDriver = "com.mysql.jdbc.Driver"; String mysqlUrl = "jdbc:mysql://localhost:3306/mybase"; String mysqlUser = "root"; String mysqlPass = "111"; String oracleDriver = "oracle.jdbc.driver.OracleDriver"; String oracleUrl = "jdbc:oracle:thin:@localhost:1521:XE"; String userName = "zl"; String passWord = "444"; String sql = "select ename from emp"; try { Class.forName(oracleDriver); } catch (ClassNotFoundException e) { System.out.println("找不到驱动"); e.printStackTrace(); } Connection conn = null; try { conn = DriverManager.getConnection(oracleUrl, userName,passWord ); } catch (SQLException e) { System.out.println("数据库连接错误"); e.printStackTrace(); } Statement st = null; try { st = conn.createStatement(); } catch (SQLException e) { System.out.println("创建数据库声明类错误"); e.printStackTrace(); } boolean flag = false; int rows = 0; ResultSet rs = null; try { flag = st.execute(sql); rows = st.executeUpdate(sql); rs = st.executeQuery(sql); while(rs.next()){ //通过列的标号来查询数据; String name =rs.getString(1); //通过列名来查询数据 String name2 = rs.getString("ename"); System.out.println(name); } } catch (SQLException e) { System.out.println("测试--"); e.printStackTrace(); } //关闭数据连接对象 try { if(rs!= null){ rs.close(); } if(st!= null){ st.close(); } if(conn!=null){ conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
赞 (0)