注册驱动(只做一次)
建立连接(Connection)
创建执行 SQL的语句(Statement)
执行查询(executeQuery)
处理执行结果(ResultSet)
释放资源
//最简单的JDBC MySQL
static void test() throws SQLException, ClassNotFoundException {
//1.注册驱动
//DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Class.forName("com.mysql.jdbc.Driver");
//2.建立连接
//建立连接原则:晚建立,早释放
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydata", "username", "password");
//3创建语句
Statement st = conn.createStatement();
//4.执行结果
ResultSet rs = st.executeQuery("select * from customers");
//5.处理结果
while (rs.next()) {
System.out.println(rs.getObject(1) + "\t" + rs.getObject(2) + "\t" + rs.getObject(3));
}
//6.释放资源
rs.close(); st.close(); conn.close();
}
--------------------------------------------------
日期处理
"ps.setDate"要求传入的是
java.sql 里面的Date, 而“Date bir”是util里面的Date
把父类赋给子类是不可以的,所以要进行转型处理.
static void create(int id, String name, Date bir, float money) throws Exception {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
// 3创建语句
String sql = "insert into user values(?,?,?,?)";
ps = conn.prepareStatement(sql);
ps.setInt(1, id);
ps.setString(2, name);
//Date要进行转型处理
ps.setDate(3, new java.sql.Date(bir.getTime()));
ps.setFloat(4, money);
// 4.执行结果
int i = ps.executeUpdate();
System.out.println("i=" + i);
} finally {
JdbcUtils.free(rs, ps, conn);
}
}
--------------------------------------------------
处理大文本
//创建大文本
static void create() throws Exception {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
// 3创建语句
String sql = "insert into clob_txt(txt) values(?)";
ps = conn.prepareStatement(sql);
File file = new File("D:/Servlet Jsp/JDBC/src/Test.java");
BufferedReader reader = new BufferedReader(new FileReader(file));
ps.setCharacterStream(1, reader, (int)file.length());
// 4.执行结果
int i = ps.executeUpdate();
reader.close();
System.out.println("i=" + i);
} finally {
JdbcUtils.free(rs, ps, conn);
}
}
//读取大文本
static void read() throws Exception {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
// 3创建语句
String sql = "select txt from clob_txt";
st = conn.createStatement();
// 4.执行结果
rs = st.executeQuery(sql);
// 5.处理结果
while (rs.next()) {
Reader reader = rs.getCharacterStream(1);
File file = new File("D:/Servlet Jsp/JDBC/src/Test_bak.java");
Writer write = new BufferedWriter(new FileWriter(file));
char[] buf = new char[1024];
int len = reader.read(buf);
while (len != -1) {
write.write(buf);
len = reader.read(buf);
}
write.close();
reader.close();
}
} finally {
JdbcUtils.free(rs, st, conn);
}
}
-----------------------------------------------------
处理二进制数据
static void create() throws Exception {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
// 3创建语句
String sql = "insert into clob_bit(big_bit) values(?)";
ps = conn.prepareStatement(sql);
File file = new File("D:/Install/Temporary file/av-376345.jpg");
InputStream in = new BufferedInputStream(new FileInputStream(file));
ps.setBinaryStream(1, in, (int)file.length());
// 4.执行结果
int i = ps.executeUpdate();
in.close();
System.out.println("i=" + i);
} finally {
JdbcUtils.free(rs, ps, conn);
}
}
static void read() throws Exception {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
// 3创建语句
String sql = "select big_bit from clob_bit";
st = conn.createStatement();
// 4.执行结果
rs = st.executeQuery(sql);
// 5.处理结果
while (rs.next()) {
InputStream in = rs.getBinaryStream(1);
File file = new File("D:/Install/av-376345_bak.jpg");
OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
byte[] buf = new byte[1024];
int len = in.read(buf);
while (len != -1) {
out.write(buf);
len = in.read(buf);
}
out.close();
in.close();
}
} finally {
JdbcUtils.free(rs, st, conn);
}
}
--------------------------------------------------
create table user
(
id int primary key auto_increment,
name varchar(30),
birthday date,
money float
);
public class User {
private int id;
private String name;
private Date birthday;
private float money;
public int getId() {
return id;
}
public User setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public User setName(String name) {
this.name = name;
}
public Date getBirthday() {
return birthday;
}
public User setBirthday(Date birthday) {
this.birthday = birthday;
}
public float getMoney() {
return money;
}
public User setMoney(float money) {
this.money = money;
}
}
public interface UserDao {
//添加用户
public void addUser(User user);
//根据id查询用户
public User getUser(int userId);
//根据用户名查询用户
public User findUser(String loginName, String password);
//更新用户信息
public void update(User user);
//删除用户
public void delete(User user);
}
public class UserDaoImpl implements UserDao {
public void addUser(User user) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
String sql = "insert into user(name, birthday, money) values(?,?,?)";
ps = conn.prepareStatement(sql);
ps.setString(1, user.getName());
ps.setDate(2, new java.sql.Date(user.getBirthday().getTime()));
ps.setFloat(3, user.getMoney());
ps.executeUpdate();
}catch(SQLException e){
throw new DaoException(e.getMessage(), e);
} finally {
JdbcUtils.free(rs, ps, conn);
}
}
public void delete(User user) {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
st = conn.createStatement();
String sql = "delete from user where id =" + user.getId();
st.executeUpdate(sql);
} catch(SQLException e){
throw new DaoException(e.getMessage(), e);
} finally {
JdbcUtils.free(rs, st, conn);
}
}
public User findUser(String loginName, String password) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
User user = null;
try {
conn = JdbcUtils.getConnection();
// 3创建语句
String sql = "select id, name, birthday, money from user where name =?";
ps = conn.prepareStatement(sql);
ps.setString(1, loginName);
// 4.执行结果
rs = ps.executeQuery();
// 5.处理结果
while (rs.next()) {
user = mappingUser(rs);
}
} catch(SQLException e){
throw new DaoException(e.getMessage(), e);
} finally {
JdbcUtils.free(rs, ps, conn);
}
return user;
}
public User getUser(int userId) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
User user = null;
try {
conn = JdbcUtils.getConnection();
// 3创建语句
String sql = "select id, name, birthday, money from user where id =?";
ps = conn.prepareStatement(sql);
ps.setInt(1, userId);
// 4.执行结果
rs = ps.executeQuery();
// 5.处理结果
while(rs.next()) {
user = mappingUser(rs);
}
} catch(SQLException e){
throw new DaoException(e.getMessage(), e);
} finally {
JdbcUtils.free(rs, ps, conn);
}
return user;
}
private User mappingUser(ResultSet rs) throws SQLException {
User user = new User();
user.setId(rs.getInt("id"));
user.setName(rs.getString("name"));
user.setBirthday(rs.getDate("birthday"));
user.setMoney(rs.getFloat("money"));
return user;
}
public void update(User user) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
String sql = "update user set name=?,birthday=?,money=? where id = ?";
ps = conn.prepareStatement(sql);
ps.setString(1, user.getName());
ps.setDate(2, new java.sql.Date(user.getBirthday().getTime()));
ps.setFloat(3, user.getMoney());
ps.setInt(4, user.getId());
ps.executeUpdate();
} catch(SQLException e){
throw new DaoException(e.getMessage(), e);
} finally {
JdbcUtils.free(rs, ps, conn);
}
}
}
public class DaoException extends RuntimeException {
public DaoException() {
super();
}
public DaoException(String message, Throwable cause) {
super(message, cause);
}
public DaoException(String message) {
super(message);
}
public DaoException(Throwable cause) {
super(cause);
}
}
public class TestUserDao {
public static void main(String[] args) {
//UserDao ud = DaoFactory.getInstance().getUserDao();
UserDao ud = new UserDaoImpl();
//创建一个user
User user3 = new User();
user3.setName("bob7");
user3 .setBirthday(new Date());
user3.setMoney(1000.0f);
//添加用户
ud.addUser(user3);
//更新用户
User u = ud.getUser(11);
u.setMoney(999.0f);
ud.update(u);
//通过 id删除用户
ud.delete(ud.getUser(9));
}
}
分享到:
相关推荐
标题中的“testMySql测试jdbc for mysql”表明这是一个关于使用Java JDBC(Java Database Connectivity)连接MySQL数据库的测试项目。在Java编程中,JDBC是Java平台标准的一部分,它允许Java程序与各种数据库进行...
**JDBC for MySQL 5.1.6** Java Database Connectivity (JDBC) 是Java平台上的一个标准API,它允许Java程序与各种类型的数据库进行交互。MySQL是一个流行的开源关系型数据库管理系统,广泛应用于Web应用程序和各种...
Class.forName("com.mysql.jdbc.Driver"); ``` 2. **建立连接**:通过`DriverManager.getConnection()`方法创建到MySQL服务器的连接。连接字符串通常包含数据库URL、用户名和密码,如: ```java String url = ...
mysql-connector-java-gpl-5.1.34.msi 官网下载
用来连接Oracle,sqlServer2000,MySQL数据库的驱动(JDBC)(ojdbc6.jar msbase.jar mssqkserver.jar msutil.jar mysql-connector-java)
标题中的“Jdbc Driver for MySql Oracle”指的是Java Database Connectivity (JDBC)驱动程序,这是Java编程语言中用于与关系数据库进行交互的一种接口。在Java应用中,JDBC驱动是连接MySQL和Oracle这两种不同数据库...
Class.forName("com.mysql.cj.jdbc.Driver"); ``` 3. **建立连接**:使用`DriverManager.getConnection()`方法创建到数据库的连接。这需要提供数据库URL、用户名和密码: ```java String url = "jdbc:mysql://...
这通常通过`Class.forName()`方法实现,参数是驱动类的全限定名,例如:“com.mysql.jdbc.Driver”。 2. **建立连接**:使用`DriverManager.getConnection()`方法创建数据库连接。该方法需要数据库URL、用户名和...
本案例将探讨如何使用JDBC连接MySQL数据库,并通过实际的代码示例讲解整个过程。我们将涉及以下知识点: 1. **JDBC驱动注册**: 在Java中,连接MySQL数据库首先需要加载并注册JDBC驱动。MySQL的JDBC驱动类是`...
Class.forName("com.mysql.cj.jdbc.Driver"); } catch (ClassNotFoundException e) { throw new RuntimeException("Driver not found", e); } } // 获取数据库连接 public static Connection getConnection...
1. **加载驱动**:在Java程序中,通过`Class.forName()`方法加载MySQL的JDBC驱动,例如`Class.forName("com.mysql.jdbc.Driver")`。 2. **建立连接**:使用`DriverManager.getConnection()`方法,传递数据库URL、...
在"JAVA JDBC-mysql练习"这个主题中,我们将深入探讨如何使用JDBC与MySQL数据库进行交互。MySQL是一种广泛使用的开源关系型数据库管理系统,其与Java的集成是通过JDBC实现的。 首先,我们需要了解JDBC的基本步骤: ...
1. 加载驱动:通过`Class.forName()`方法加载MySQL的JDBC驱动,例如`Class.forName("com.mysql.jdbc.Driver")`。 2. 建立连接:使用`DriverManager.getConnection()`方法,提供数据库URL、用户名和密码来建立连接,...
1. 加载驱动:使用`Class.forName()`方法加载MySQL JDBC驱动。 2. 创建连接:通过`DriverManager.getConnection()`方法创建数据库连接,需要提供数据库URL、用户名和密码。 3. 获取Statement或PreparedStatement对象...
Class.forName("com.mysql.cj.jdbc.Driver"); // 数据库连接信息 String url = "jdbc:mysql://localhost:3306/mydatabase"; String user = "username"; String password = "password"; try { // 建立连接 ...
1. 加载驱动:使用`Class.forName()`方法加载MySQL JDBC驱动的类。 ```java Class.forName("com.mysql.cj.jdbc.Driver"); ``` 请注意,不同版本的MySQL JDBC驱动可能需要加载不同的类名,例如旧版本可能需要`...
Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/your_database", "username", "password"); Statement stmt = conn.createStatement(); ...
Connector/J 5.1 支持Mysql 4.1、Mysql 5.0、Mysql 5.1、Mysql 6.0 alpha这些版本。 Connector/J 5.0 支持MySQL 4.1、MySQL 5.0 servers、distributed transaction (XA)。 Connector/J 3.1 支持MySQL 4.1、MySQL 5.0...
在上述代码中,我们首先通过`Class.forName()`加载MySQL的JDBC驱动,然后使用`DriverManager.getConnection()`方法建立到数据库的连接。URL参数`jdbc:mysql://localhost:3306/mydatabase`指定了服务器地址、端口号和...
1. 加载JDBC驱动:`Class.forName("com.mysql.jdbc.Driver")` 2. 创建数据库连接:`Connection conn = DriverManager.getConnection(url, username, password);` 3. 创建Statement或PreparedStatement对象,用于执行...