JDBC连接SQL server 实现增删查改(IDEA整合)
一、环境搭建
1. SQL server 2019 和 SSMS
官网:https://www.microsoft.com/zh-cn/sql-server/sql-server-2019
SQL server 2019下载地址:https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads
下载开发者版本:
具体安装步骤和SSMS的安装可参考:https://blog.csdn.net/m0_47180536/article/details/115406888
2. idea 2021.1
下载地址:https://www.jetbrains.com/zh-cn/idea/download/#section=windows
虽然是收费的,但是可以免费使用30天,也可以申请学生免费使用
3. SQL server连接包
下载之后解压得到如下文件:
有3个版本的jre供你选择,根据自己电脑安装的jdk版本进行选择。
4. 创建数据库及数据表
安装完成SQL server 2019和SSMS之后,打开SSMS
填写你的密码,点击连接
右击数据库,选择新建数据库
数据库名称为test,点击确定,即可看到创建的数据库test
点击新建查询,并看使用的数据库是否为你所创建的数据库
在编辑区写建表的sql语句,
create table users( --创建表名为users的表
id int primary key identity(1,1), --字段名为id,是主键,自动增长,从1开始,每次增长1
name varchar(50), --字段名为name
password varchar(50) --字段名为password
)
点击执行,看到命令已完成表示建表成功!
插入数据
insert into users values('杨小强','123456'); --不用插入id的值是因为设置了id字段自动增长,SQL server自动帮我们完成插入
insert into users values('李华','099876');
insert into users values('张三','246751');
若消息显示3个1行受影响,表示插入数据成功,可用查询语句查看: SELECT * FROM users
至此,环境已经准备好了!
二、JDBC连接SQL server
项目地址:https://github.com/XQ-yang/JDBC
1. IDEA创建java项目,将SQLserver的连接jar包导入项目依赖
打开项目结构(快捷键Ctrl+Shift+Alt+S),选择Libraries,点击“+”,选择java,之后就选择你下载后解压的jdk对应版本的jar包
2. 创建包jdbc,编写java类
DBUtil类
注册驱动及释放资源
package JDBC;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
/**
* @Author: XQ-Yang
* @Date: 2021/5/5 0005
* @Tools: IntelliJ IDEA
* @Remember: Be professional every day
**/
public class DBUtil {
//加载JDBC驱动
private String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
//连接服务器和数据库
private String dbURL = "jdbc:sqlserver://localhost:1433; DatabaseName=test";
//默认用户名,一般为sa
private String userName = "sa";
//用户名密码
private String password = "123456";
/**
* 注册驱动
* @return
*/
public Connection getConn() {
Connection dbConn = null;
try {
Class.forName(driverName);
dbConn = DriverManager.getConnection(dbURL, userName, password);
// 如果连接成功 控制台输出
System.out.println("SQL server数据库连接成功!");
} catch (Exception e) {
System.out.println("SQL server数据库连接失败?????");
e.printStackTrace();
}
return dbConn;
}
/**
* 释放资源
* @param rs
* @param pstm
* @param conn
* @throws Exception
*/
public void closeConn(ResultSet rs, PreparedStatement pstm, Connection conn) throws Exception {
if (rs != null) {
rs.close();
}
if (pstm != null) {
pstm.close();
}
if (conn != null) {
conn.close();
}
}
}
User类
实体类,映射数据库中的字段
package JDBC;
/**
* @Author: XQ-Yang
* @Date: 2021/5/5 0005
* @Tools: IntelliJ IDEA
* @Remember: Be professional every day
**/
public class User {
public int id;
public String name;
public String password;
public int getId() {
return id;
}
public void setId(int 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 + '\'' +
'}';
}
}
UserDao类
实现增删查改功能
package JDBC;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
/**
* @Author: XQ-Yang
* @Date: 2021/5/5 0005
* @Tools: IntelliJ IDEA
* @Remember: Be professional every day
**/
public class UserDao {
DBUtil db = new DBUtil();
/**
* 插入用户信息
*/
public void insertUser(User user) throws Exception {
Connection conn = db.getConn();
PreparedStatement pstm;
//sql语言
String sql_insert = "insert into users values(?,?)";
pstm = conn.prepareStatement(sql_insert);
//填充sql语句中的?
pstm.setString(1, user.getName());
pstm.setString(2, user.getPassword());
//使用executeUpdate函数执行sql语句
int row = pstm.executeUpdate();
if (row > 0) {
System.out.println("新增用户成功, " + row + "行受到影响");
} else {
System.out.println("新增用户失败!");
}
//释放对数据库的连接
db.closeConn(null, pstm, conn);
}
/**
* 修改用户信息
*/
public void updateUser(int id, User user) throws Exception {
Connection conn = db.getConn();
PreparedStatement pstm;
String sql_update = "update users set password=? where id=?";
pstm = conn.prepareStatement(sql_update);
// pstm.setString(1,user.getUsername()); //运行报错说与mysql关键字相同,故不修改用户名
pstm.setString(1, user.getPassword());
pstm.setInt(2, id);
int row = pstm.executeUpdate();
if (row > 0) {
System.out.println("修改用户信息成功, " + row + "行受到影响");
} else {
System.out.println("修改用户信息失败!");
}
db.closeConn(null, pstm, conn);
}
/**
* 删除用户信息
*/
public void deleteUser(int id) throws Exception {
Connection conn = db.getConn();
PreparedStatement pstm;
String sql_delete = "delete from users where id=?";
pstm = conn.prepareStatement(sql_delete);
pstm.setInt(1, id);
int row = pstm.executeUpdate();
if (row > 0) {
System.out.println("删除用户成功, " + row + "行受到影响");
} else {
System.out.println("删除用户失败!");
}
db.closeConn(null, pstm, conn);
}
/**
* 查询全部用户
*/
public void findUser() throws Exception {
Connection conn = db.getConn();
PreparedStatement pstm;
ResultSet res;
String sql_find = "select * from users ";
pstm = conn.prepareStatement(sql_find);
res = pstm.executeQuery();
System.out.println("查询用户成功!!");
System.out.println("id\tname\tpassword");
while (res.next()) {
System.out.println(res.getInt(1) + "\t" +
res.getString(2) + "\t" + res.getString(3));
}
db.closeConn(res, pstm, conn);
}
/**
* 根据查询用户
*/
public void findUserbyid(int id) throws Exception {
Connection conn = db.getConn();
PreparedStatement pstm;
ResultSet res;
String sql_find = "select * from users where id = ?";
pstm = conn.prepareStatement(sql_find);
pstm.setInt(1, id);
res = pstm.executeQuery();
if (res.next()) {
System.out.println("找到了该用户!");
System.out.println("id\tname\tpassword");
System.out.println(res.getInt(1) + "\t" +
res.getString(2) + "\t" + res.getString(3));
} else {
System.out.println("未找到该用户!");
}
db.closeConn(res, pstm, conn);
}
/**
* 统计用户
*/
public void countUser() throws Exception {
Connection conn = db.getConn();
PreparedStatement pstm;
ResultSet res;
String sql_count = "select count(*) from users";
pstm = conn.prepareStatement(sql_count);
res = pstm.executeQuery();
int count = 0;
if (res.next()) {
count = res.getInt(1);
System.out.println("用户数有" + count + "个!");
} else {
System.out.println("没有用户!");
}
db.closeConn(res, pstm, conn);
}
}
Test类
用于测试增删查改功能
package JDBC;
/**
* @Author: XQ-Yang
* @Date: 2021/5/4 0004
* @Tools: IntelliJ IDEA
* @Remember: Be professional every day
**/
public class Test {
public static void main(String[] args) throws Exception {
UserDao dao = new UserDao();
User user = new User();
dao.findUser();
}
}
Test类运行结果:
运行结果出现了中文乱码,得处理一下。