JDBC连接数据库的五种方式

方式一
	public void connectionTest() throws SQLException {
		//定义URL
		String url = "jdbc:mysql://localhost:3306/test";
		//创建driver
		Driver driver = new com.mysql.jdbc. Driver();
		//通过驱动来获取链接
		Properties pro = new Properties();
		pro.setProperty("user", "root");
		pro.setProperty("password",	"root");
		Connection conn = driver.connect(url, pro);
		System.out.println(conn);
	}

这是最通俗的连接方式
问题是应用程序和Mysql的jdbc的实现类发生了直接的耦合

方式二
public void connectionTest2() throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException {
		//定义URL
		String url = "jdbc:mysql://localhost:3306/test";
		//创建driver
		String driverStr = "com.mysql.jdbc.Driver";//Driver类的全类名
		Driver driver =  null;
		driver =(Driver) Class.forName(driverStr).newInstance();
		//通过驱动来获取链接
		Properties pro = new Properties();
		pro.setProperty("user", "root");
		pro.setProperty("password",	"root");
		Connection conn = driver.connect(url, pro);
		System.out.println(conn);
	}

这种方式使用反了射机制来解除耦合

方式三
	public void connectionTest3() throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException {
		//定义URL
		String url = "jdbc:mysql://localhost:3306/test";
		//创建driver
		String driverStr = "com.mysql.jdbc.Driver";//Driver类的全类名
		Driver driver =  null;
		driver =(Driver) Class.forName(driverStr).newInstance();
		//注册驱动
		DriverManager.registerDriver(driver);
		//通过驱动来获取链接
		Properties pro = new Properties();
		pro.setProperty("user", "root");
		pro.setProperty("password",	"root");
		Connection conn = driver.connect(url, pro);
		System.out.println(conn);
	}

这种 DriverManager使用注册驱动

方式四
public void connectionTest4() throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException {
		//定义URL
		String url = "jdbc:mysql://localhost:3306/test";
		//创建driver
		String driverStr = "com.mysql.jdbc.Driver";//Driver类的全类名
		//创建用户名和密码
		String user = "root";
		String password="root";
		//加载mysql的Dirver
		Class.forName(driverStr);
		 
		Connection conn = DriverManager.getConnection(url, user,password);
		System.out.println(conn);
	}

但是方式四的连接属性还是采用了硬编码的方式

方式五

编写一个jdbc.properties的配置文件

url=jdbc:mysql://localhost:3306/test
driver =com.mysql.jdbc.Driver
user=root
password=root
public void connectionTest5() throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException, IOException {
		//第一步加载配置文件
		InputStream in =this.getClass().getClassLoader().getSystemResourceAsStream("jdbc.properties");
		
		Properties pro = new Properties();
		pro.load(in);
		//定义URL
		String url = pro.getProperty("url");
		//从配置文件中获取链接属性
		String driverStr = pro.getProperty("driver");//Driver类的全类名
		String user = pro.getProperty("user");
		String password=pro.getProperty("password");
		//加载mysql的Dirver
		Class.forName(driverStr);
		Connection conn = DriverManager.getConnection(url, user,password);
		System.out.println(conn);
	}

这个就解决了硬编码问题

JDBC访问数据库的步骤 1. 新建java项目:JDBC,新建 class文件:TestJDBC 2. JDBC用到的类库基本都位于java.sql.*包中,程序中引入该包: Import java.sql.*; 3. 添加要用的数据库中的包,找到数据库中的Driver.class文件: 项目名上点右键,Build Path—Add External Archives… 构建路径----添加外部归档 加入mysql-connector-java-5.1.12 4. 从包中找到要用的驱动,展开包,从中找到Driver.class,编程时,先把这个类的驱动new一个实例对象出来,告诉DriverManage,要连到哪种数据库上: 方法一:Class.forName(“com.mysql.jdbc.Driver”); Class: java.lang中的特殊类,类的装载器; forName: 会抛异常; com.mysql.jdbc.Driver中的Driver会new一个它的实例对象 方法二:new com.mysql.jdbc.Driver(); new出来后会自动向DriverManage注册。 5. 得到数据库的连接: Connection conn=DriverManager.getConnection (数据库的连接串,用户名,密码); 数据库的连接串:“jdbc:mysql://localhost:3306/books” 用户名: “root” 密码: “111” 程序调试: import java.sql.*; public class TestJDBC { public static void main(String[] args)throws Exception { Class.forName("com.mysql.jdbc.Driver"); Connection conn=DriverManager.getConnection ("jdbc:mysql://localhost:3306/books?","root","111"); System.out.println("Connection Successful!"); } } * *对数据库表的操作通常有:executeQuery() executeUpdate() 6. (1)应用Statement接口 获取Statement对象,通过Statement对象执行SQL语句: Statement stmt=con.createStatement(); 执行SQL查询,返回给结果集对象: ResultSet rs=stmt. executeQuery(“select * from 表名”); 或 表名”+条件); 遍历访问数据表:while(rs.next()) 以各种类型显示输出:rs.get×××(“字段名”) (2)应用PreparedStatement接口 (p203) 执行数据更新executeUpdate():insert、update、delete SQL语句的创建:String sql=“sql命令”; 创建PreparedStatement的对象: pstmt=con. PrepareStatement(sql); 执行赋值操作(“?”占位符的用法): 执行:insert、update、delete result=pstmt. executeUpdate(); result类型为整型,返回一个整数,小于零操作没成功 7.关闭不再使用的 如:rs.close(); stmt.close(); con.close(); JDBC编程步骤总结: 1. Load the Driver:Class.forName(); 2. Connect the DateBase: DriveManager.getConnection() 3. Execute the SQL: (1) Connection.createStatement() Connection.prepareStatement(sql) (2)Statement.executeQuery() (3)Statement.executeUpdate() 4. Retrieve the result data: 循环取得结果while(rs.next()) 5. Show the result data:将遍历的结果记录显示出来 6.Close:结束时关闭 //完善的JDBC程序 import java.sql.*; public class TestJDBC { public static void main(String[] args) { Connection conn=null; Statement stmt=null; ResultSet rs=null; try{ Class.forName("com.mysql.jdbc.Driver"); conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/books?","root","111"); System.out.println("Connection Successful!"); stmt=conn.createStatement(); rs=stmt.executeQuery("select * from titles"); while (rs.next()){ System.out.println(rs.getString("isbn")+" "+rs.getString("title")); } }catch(ClassNotFoundException e){ e.printStackTrace(); }catch(SQLException e){ e.printStackTrace(); }finally{ try{ if(rs!=null){ rs.close(); rs=null; } if(stmt!=null){ stmt.close(); stmt=null; } if(con!=null){ con.close(); con=null; } }catch(SQLException e){ e.printStackTrace(); } } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

如我一般的人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值