您的位置:首页 > 数据库 > MySQL

jdbc操作mysql数据库

2015-11-20 15:25 513 查看
如何操作mysql数据库进行crud:

第一步:创建数据库

DROP TABLE IF EXISTS `jdbc_user`;
CREATE TABLE `jdbc_user` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键id',
`name` varchar(255) DEFAULT NULL COMMENT '户用名',
`password` varchar(255) DEFAULT NULL COMMENT '户用密码',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;


第二步:导入mysql-connector-java的jar包

第三步:创建实体类:

package com.jdbc.entity;

/**
* 用户实体类 如果觉得 get / set 方法比较冗余,可以考虑使用lombok
*
* @author ITDragon
*
*/
public class User implements java.io.Serializable {

/**
* 第一步:实体类序列化
* 第二步:定义属性
* 第三步:生成get/set方法
* 第四步:创建带主键参数的构造方法
* 第五步:生成toString()方便看结果
*/

private Integer id; // 用户id
private String name; // 用户名
private String password; // 用户密码

public User() {
}

public User(Integer id) {
this.id = id;
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", password=" + password
+ "]";
}

}
第四步:创建链接数据库工具类

package com.jdbc.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

/**
* 数据库连接类
* @author ITDragon
*
*/
public class ConnectionUtil {

/**
* 第一步:加载驱动
* 第二步:链接数据库
* 第三步:一定要关闭流
* 第四步:测试是否连接成功
*/

private static String DRIVER = "com.mysql.jdbc.Driver"; 		// 数据库驱动
private static String URL = "jdbc:mysql://localhost:3306/test";	// 访问数据库路径
private static String NAME = "root";							// 数据库用户名
private static String PASSWORD = "root";						// 数据库密码

public static Connection getConnection() {
Connection connection = null;
try {
// 加载驱动
Class.forName(DRIVER);
// 连接数据库
connection = DriverManager.getConnection(URL, NAME, PASSWORD);
return connection;
} catch (Exception e) {
return null;
}
}

// 关闭流
public static void closeConnection(Connection connection) {
try {
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}

public static void closeStatement(Statement statement) {
try {
statement.close();
} catch (Exception e) {
e.printStackTrace();
}
}

public static void closePreparedStatement(PreparedStatement pStatement) {
try {
pStatement.close();
} catch (Exception e) {
e.printStackTrace();
}
}

public static void closeResultSet(ResultSet rs) {
try {
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
}

// 测试数据库是否链接成功
public static void main(String[] args) {
System.out.println(getConnection());
}

}

执行出现类似于com.mysql.jdbc.JDBC4Connection@1b8cdd5则表示执行成功

第五步:核心代码

package com.jdbc.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import com.jdbc.entity.User;
import com.jdbc.util.ConnectionUtil;

public class UserDao {
/**
*
* 插入数据(根据JavaBean的内容插入;所以要导入Dao类) 方法名:saveDao<BR>
* 创建人:ITDragon <BR>
* 时间:2015年2月6日-下午8:33:09 <BR>
*
* @param dao
* @return boolean<BR>
* @exception <BR>
* @since 1.0.0
*/
public static boolean saveDao(User user) {
String sql = "insert into jdbc_user(name,password) values(?,?)";
Connection connection = null;
PreparedStatement pStatement = null;
try {
connection = ConnectionUtil.getConnection();
pStatement = connection.prepareStatement(sql);
pStatement.setString(1, user.getName());
pStatement.setString(2, user.getPassword());
int count = pStatement.executeUpdate();
return count > 0 ? true : false;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
ConnectionUtil.closePreparedStatement(pStatement);
ConnectionUtil.closeConnection(connection);
}
}
/**
*
* 查询数据 方法名:findDaos<BR>
* 创建人:ITDragon <BR>
* 时间:2015年2月6日-下午8:55:05 <BR>
*
* @return List<Dao><BR>
* @exception <BR>
* @since 1.0.0
*/
public static List<User> findUsers() {
String sql = "select * from jdbc_user";
Connection connection = null;
PreparedStatement pStatement = null;
ResultSet rs = null;
List<User> users = null;
try {
connection = ConnectionUtil.getConnection();
pStatement = connection.prepareStatement(sql);
rs = pStatement.executeQuery();
users = new ArrayList<User>();
while (rs.next()) {
User user = new User();
user.setId(rs.getInt("id"));
user.setName(rs.getString("name"));
user.setPassword(rs.getString("password"));
users.add(user);
}
return users;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
ConnectionUtil.closeResultSet(rs);
ConnectionUtil.closePreparedStatement(pStatement);
ConnectionUtil.closeConnection(connection);
}
}
/**
*
* 根据主键id删除 方法名:deleteUser<BR>
* 创建人:ITDragon <BR>
* 时间:2015年2月6日-下午9:03:55 <BR>
*
* @param id
* @return boolean<BR>
* @exception <BR>
* @since 1.0.0
*/
public static boolean deleteUser(Integer id) {
String sql = "delete from jdbc_user where id = ?";
Connection connection = null;
PreparedStatement pStatement = null;
try {
connection = ConnectionUtil.getConnection();
pStatement = connection.prepareStatement(sql);
pStatement.setInt(1, id);
int count = pStatement.executeUpdate();
return count > 0 ? true : false;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
ConnectionUtil.closePreparedStatement(pStatement);
ConnectionUtil.closeConnection(connection);
}
}
/**
*
* 根据主键id修改数据 方法名:updateUser<BR>
* 创建人:ITDragon <BR>
* 时间:2015年2月6日-下午9:17:03 <BR>
*
* @param name
* @param password
* @param id
* @return boolean<BR>
* @exception <BR>
* @since 1.0.0
*/
public static boolean updateUser(String name, String password, Integer id) {
// name 和 password之间只能用 ","隔开
String sql = "update jdbc_user set name = ? , password = ?  where id = ?";
Connection connection = null;
PreparedStatement pStatement = null;
try {
connection = ConnectionUtil.getConnection();
pStatement = connection.prepareStatement(sql);
pStatement.setString(1, name);
pStatement.setString(2, password);
pStatement.setInt(3, id);
int count = pStatement.executeUpdate();
return count > 0 ? true : false;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
ConnectionUtil.closePreparedStatement(pStatement);
ConnectionUtil.closeConnection(connection);
}
}
}

第六步:测试类

package com.jdbc.test;

import java.util.List;

import org.junit.Test;

import com.jdbc.dao.UserDao;
import com.jdbc.entity.User;

/**
* 测试User的crud
* @author ITDragon
*
*/
public class UserTest {

@Test
public void findUserTest(){
List<User> users= UserDao.findUsers();
for (User user : users) {
System.out.println(user);
}
}

@Test
public void saveUserTest(){
User user = new User();
user.setName("ITDragon");
user.setPassword("麻麻说密码太长容易记得");
boolean flag = UserDao.saveDao(user);
if (flag) {
System.out.println(user.getName()+"保存成功");
} else {
System.out.println("保存失败");
}
}

@Test
public void updateUserTest(){
boolean flag = UserDao.updateUser("NewITDragon", "麻麻说错了", 1);
if (flag) {
System.out.println("更新成功");
} else {
System.out.println("更新失败");
}
}

@Test
public void deleteUserTest(){
boolean flag = UserDao.deleteUser(1);
if (flag) {
System.out.println("删除成功");
} else {
System.out.println("删除失败");
}
}

}

资料下载地址:http://download.csdn.net/detail/qq_19558705/9285827

个人主页:http://www.itit123.cn/ 更多干货等你来拿

有什么疑问和建议可以留言。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: