其实eclipse连接SQL数据库的增删改查与之前发的eclipse连接Mysql数据库的增删改查区别不大,只有一点点地方需要改动,大家可自行发现哈。点击查看eclipse连接Mysql的增删改查
1.在SQL数据库中建表
CREATE TABLE
Users
(
id INT NOT NULL,
user_name VARCHAR(20) NOT NULL,
age INT NOT NULL,
sex INT NOT NULL,
create_dt DATE NOT NULL,
PRIMARY KEY (id)
)
插入数据
Insert into Users values(1,'zhangsan',25,1,'2016-9-9'),
(2,'lisi',23,0,'2016-9-8'),
(3,'wangwu',21,0,'2016-9-7');
查询结果如下:
打开eclipse(已成功连接)
整体结构
定义一个bean类UserVO
package com.test.sql;
import java.util.Date;
public class UserVO {
private int id;
private String userName;
private int age;
private int sex;
private Date createDt;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
public Date getCreateDt() {
return createDt;
}
public void setCreateDt(Date createDt) {
this.createDt = createDt;
}
@Override
public String toString() {
return "UserVO [id=" + id + ", userName=" + userName + ", age=" + age
+ ", sex=" + sex + ", createDt=" + createDt + "]";
}
}
改造Util类,用于获取数据库连接
package com.test.sql;
import java.sql.Connection;
import java.sql.DriverManager;
public class DBUtil {
private static final String URI = "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=test";
private static final String userName="sa";//你的数据库用户名
private static final String userPwd="123";//你的密码
private static final String DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
public static Connection connectDB() throws Exception {
//1、加载数据库驱动
Class.forName(DRIVER);
//2、获取数据库连接
Connection conn = DriverManager.getConnection(URI,userName,userPwd);
return conn;
}
}
准备工作完成后,定义一个UserDao类,用于操作数据库的增删改查
1.查询全部
package com.test.sql;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public class UserDao {
public List<UserVO> queryAll() throws Exception {
Connection conn = DBUtil.connectDB();
String sql = "SELECT * FROM users";
List<UserVO> userList = new ArrayList<UserVO>();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()) {
UserVO user = new UserVO();
user.setId(rs.getInt("id"));
user.setUserName(rs.getString("user_name"));
user.setAge(rs.getInt("age"));
user.setSex(rs.getInt("sex"));
user.setCreateDt(rs.getDate("create_dt"));
userList.add(user);
}
return userList;
}
public static void main(String[] args) {
UserDao dao = new UserDao();
try {
List<UserVO> userList = dao.queryAll();
for(UserVO user : userList) {
System.out.println(user);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.test.sql;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class UserDao {
public List<UserVO> queryByParams(List<Map<String, Object>> params) throws Exception {
Connection conn = DBUtil.connectDB();
StringBuilder sql = new StringBuilder("SELECT * FROM Users WHERE 1=1 ");
for(Map<String, Object> param : params) {
sql.append(" and ");
sql.append(" " + param.get("col") + " ");
sql.append(" " + param.get("rel") + " ");
sql.append(" " + param.get("value") + " ");
}
System.out.println(sql.toString());
List<UserVO> userList = new ArrayList<UserVO>();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql.toString());
while(rs.next()) {
UserVO user = new UserVO();
user.setId(rs.getInt("id"));
user.setUserName(rs.getString("user_name"));
user.setAge(rs.getInt("age"));
user.setSex(rs.getInt("sex"));
user.setCreateDt(rs.getDate("create_dt"));
userList.add(user);
}
return userList;
}
public static void main(String[] args) {
UserDao dao = new UserDao();
List<Map<String, Object>> params = new ArrayList<Map<String,Object>>();
Map<String, Object> param1 = new HashMap<String, Object>();
param1.put("col", "user_name");
param1.put("rel", "like");
param1.put("value", "'%ang%'");
params.add(param1);
Map<String, Object> param2 = new HashMap<String, Object>();
param2.put("col", "sex");
param2.put("rel", "=");
param2.put("value", 1);
params.add(param2);
try {
List<UserVO> userList = dao.queryByParams(params);
for(UserVO user : userList) {
System.out.println(user);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.test.sql;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
public class UserDao {
public void addUser(UserVO user) throws Exception {
Connection conn = DBUtil.connectDB();
String sql = "INSERT INTO Users(id,user_name, age, sex, create_dt) "
+ " VALUES(?,?, ?, ?,?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, user.getId());
pstmt.setString(2, user.getUserName());
pstmt.setInt(3, user.getAge());
pstmt.setInt(4, user.getSex());
pstmt.setDate(5, new Date(new java.util.Date().getTime()));
pstmt.execute();
}
public static void main(String[] args) {
UserDao dao = new UserDao();
UserVO user = new UserVO();
user.setId(4);
user.setUserName("zhaosi");
user.setAge(20);
user.setSex(1);
try {
dao.addUser(user);
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.test.sql;
import java.sql.Connection;
import java.sql.PreparedStatement;
public class UserDao {
public void deleteUser(int id) throws Exception {
Connection conn = DBUtil.connectDB();
String sql = "DELETE FROM Users WHERE id = ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, id);
pstmt.execute();
}
public static void main(String[] args) {
UserDao dao = new UserDao();
try {
dao.deleteUser(1);
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.test.sql;
import java.sql.Connection;
import java.sql.PreparedStatement;
public class UserDao {
public void updateUser(UserVO user) throws Exception {
Connection conn = DBUtil.connectDB();
String sql = "UPDATE Users SET user_name=?, age=?, sex=?"
+ " WHERE id=?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, user.getUserName());
pstmt.setInt(2, user.getAge());
pstmt.setInt(3, user.getSex());
pstmt.setInt(4, user.getId());
pstmt.executeUpdate();
}
public static void main(String[] args) {
UserDao dao = new UserDao();
UserVO user = new UserVO();
user.setUserName("zhaoliu");
user.setAge(21);
user.setSex(0);
user.setId(4);
try {
dao.updateUser(user);
} catch (Exception e) {
e.printStackTrace();
}
}
}