标签:jdbc
1:通过反射机制来创建驱动管理类
package com.yangyang.jdbc; import java.sql.Connection; import java.sql.Driver; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JDBCTest { public static void main(String[] args) throws SQLException { Connection conn = null; Statement stat =null; ResultSet rs = null; int Count = 0; try { //第二种方式注册驱动,通过反射机制创建注册驱动类 Class.forName("com.yangyang.jdbc.RegisterDriver"); //获取数据库连接 String url = "jdbc:mysql://127.0.0.1:3306/jdbc"; String user = "root"; String password = "123456"; conn = DriverManager.getConnection(url,user,password); //3获取数据库操作对象 stat = conn.createStatement(); //4执行SQL语句:DQL语句->查询 String sql = "select c_id, c_name , c_zip from customers;"; rs = stat.executeQuery(sql); System.out.println(rs); //5处理查询结果 while(rs.next()){ //取数据的第一种方式 String name= rs.getString("c_name"); int id = rs.getInt("c_id"); double zip = rs.getDouble("c_zip"); System.out.println(name+"\t "+id+"\t "+zip); } } catch (ClassNotFoundException e) { e.printStackTrace(); } } } /** * 注册驱动 * @author 阳阳 * */ class RegisterDriver{ static { try { System.out.println("驱动类加载成功"); Driver driver = new com.mysql.jdbc.Driver(); DriverManager.deregisterDriver(driver); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
通过propreties读取配置文件
package com.yangyang.jdbc; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; public class JDBCTest01{ public static void main(String[] args) throws IOException, SQLException{ //----------从配置文件获取连接数据库的信息------- //通过FileReader读取配置文件 FileReader fileReader = new FileReader("conf/server.properties");; //创建属性对象 Properties pro = new Properties(); //通过属性对象的load方法将配置信息加载到内存中生成一个map集合 pro.load(fileReader); //关闭流 fileReader.close(); String driver = pro.getProperty("driver"); String url = pro.getProperty("url"); String user = pro.getProperty("user"); String password = pro.getProperty("password"); //--------连接数据库------------ Connection conn = null; Statement stmt = null; int count = 0; try { //1注册驱动 Class.forName(driver); //2获取数据库连接对象 conn = DriverManager.getConnection(url,user,password); //3获取数据库操作对象 stmt = conn.createStatement(); //4执行Sql语句 DML-> insert update delect String sql_ins = "insert into t_user(name) values (‘hanmeimei‘)"; count = stmt.executeUpdate(sql_ins); String sql_update = "update t_user set name = ‘lelei‘ where id = ‘1‘"; count = stmt.executeUpdate(sql_update); System.out.println(count); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ if(stmt != null){ stmt.close(); } if(conn != null){ conn.close(); } } } }
本文出自 “逐梦路上的Man” 博客,请务必保留此出处http://meyangyang.blog.51cto.com/12906086/1971682
标签:jdbc
原文地址:http://meyangyang.blog.51cto.com/12906086/1971682