JDBC连接数据库(上)
?创建一个以JDBC连接数据库的程序:
1、加载JDBC驱动程序
在连接数据库之前,首先要加载想要连接的数据库的驱动到JVM(Java虚拟机),
这通过java.lang.Class类的静态方法forName(String className)实现。
例如:
try{ //加载MySql的驱动类 Class.forName("com.mysql.jdbc.Driver") ; }catch(ClassNotFoundException e){ System.out.println("找不到驱动程序类 ,加载驱动失败!"); e.printStackTrace() ; }成功加载后,会将Driver类的实例注册到DriverManager类中。
URL ="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=gbk";
String url = "jdbc:mysql://localhost:3306/test";String username = "root";String password = "root";try {Connection con = DriverManager.getConnection(url, username,password);} catch (SQLException se) {System.out.println("数据库连接失败!");se.printStackTrace();}
Statement stmt = con.createStatement() ; PreparedStatement pstmt = con.prepareStatement(sql) ; CallableStatement cstmt = con.prepareCall("{CALL demoSp(? , ?)}") ;
ResultSet rs = stmt.executeQuery("SELECT * FROM ...") ; int rows = stmt.executeUpdate("INSERT INTO ...") ; boolean flag = stmt.execute(String sql) ;
while(rs.next()){ String name = rs.getString("name") ; String pass = rs.getString(1) ; // 此方法比较高效 }
if (rs != null) { // 关闭记录集try {rs.close();} catch (SQLException e) {e.printStackTrace();}}if (stmt != null) { // 关闭声明try {stmt.close();} catch (SQLException e) {e.printStackTrace();}}if (conn != null) { // 关闭连接对象try {conn.close();} catch (SQLException e) {e.printStackTrace();}}
String Driver = "com.mysql.jdbc.Driver"; // 驱动程序String URL = "jdbc:mysql://localhost:3306/test"; // 连接的URL,test为数据库名,注意修改编码类型String Username = "root"; // 用户名String Password = "root"; // 密码Connection conn;try {try {Class.forName(Driver).newInstance();} catch (InstantiationException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalAccessException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}conn = DriverManager.getConnection(URL, Username, Password);Statement stmt = (Statement) conn.createStatement();String query = "select * from test.crm_customers";ResultSet rs = stmt.executeQuery(query);while (rs.next()){System.out.println(rs.getString(1));System.out.println(rs.getString(2));}if (rs != null) { // 关闭记录集try {rs.close();} catch (SQLException e) {e.printStackTrace();}}if (stmt != null) { // 关闭声明try {stmt.close();} catch (SQLException e) {e.printStackTrace();}}if (conn != null) { // 关闭连接对象try {conn.close();} catch (SQLException e) {e.printStackTrace();}}} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}