JDBC访问数据库

Java数据库的操作

如何通过JDBC访问数据库

Java数据库连接用于在Java程序中实现数据库操作功能,它提供了执行SQL语句,访问各种数据库的方法,并为各种不同的数据库提供统一的操作接口,**java.sql包中包括了JDBC操作数据的所有的类。**具体操作步骤如下:
**(1)加载JDBC驱动器。**将数据库的JDBC驱动加载到classpath中,在基于JavaEE的Web应用开发中,通常要把目标数据库产品的JDBC驱动复制到WEB-INF/lib下
**(2)加载JDBC驱动,**并将其注册到DriverManager中。一般使用反射Class.forName(String driverName)
(3)建立数据库的连接,取得Connection对象。一般通过DriverManager.getConnection(url,username,passwd)方法实现,其中,url:连接数据库的字符串,username:连接数据库的用户 ,passwd:连接数据的密码
(4)建立Statement对象或者是PreparedStatement对象。
(5)执行SQL语句
(6)访问结果集ResultSet对象
**(7)依次将ResultSet,Statement,PreparedStatement,Connection对象关闭,**释放掉所占用的资源(因为JDBC驱动底层通常都是通过网络IO实现SQL命令与数据传输)

使用JDBC访问MySQL的例子

package com.hfh;
import java.sql.*;
public class Demo{
public static void main(String[] args ) throws Exception{	
	String user = "root";
	String password = "root";
	String url = "jdbc:mysql://localhost/hfh_db?useUnicode=true&characterEncoding=UTF-8";
	String driver = "com.mysql.jdbc.Driver";
	Connection con = null;
	Statement stmt = null;
	ResultSet rs = null;
	try {			
		Class.forName("com.mysql.jdbc.Driver");
		con = DriverManager.getConnection(url,user,password);
		stmt = con.createStatement();
		stmt.execute("insert into Employee (name,age) value('James',20)");
		stmt.execute("insert into Employee (name,age) value('Bob',25)");
		rs = stmt.executeQuery("select * from Employee");
		while (rs.next()) {
			System.out.println(rs.getInt(1) + " " + rs.getString(2)+ " " +rs.getInt(3));				
		}				
	} catch (SQLException e1) {
		e1.printStackTrace();
	}finally {
		try {
			if (rs != null) rs.close();
			if(stmt != null) stmt.close();
			if (con != null) con.close(); 
		} catch (SQLException e) {
			System.out.println(e.getMessage());
		}
	}
}

}

![Alt]在这里插入图片描述在这里插入图片描述
数据库名字最好不要取db…创建完表后,然后对表设计,把自动递增勾上

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值