首先要对SQL server的一些配置进行更改:
找到SQL server的配置管理器:然后点击进去。
找到SQL server网络配置下一级的mssqlserver的协议。把右边的,TCP/Ip的状态右击改为启动。
也可以点击属性设置,找到ip地址
把常用的ip10/ip6/ip4的地址改为本机。127.0.0.1 不能改成localhost
改完这些之后,重启SQL server服务 sqlserver(mssqlserver)
新建一个类:
public class SqlServerUtils {
public static Connection con = null;
public static Statement state = null;
public static ResultSet rs = null;
static {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//连接数据库
public static Connection getCon(){
String url = "jdbc:sqlserver://localhost:1433;databaseName=meitao";
//databaseName = 你要连接的数据库名字
String username = "sa"; //要连接的用户名
String password = "123"; //密码
try {
con = DriverManager.getConnection(url,username,password);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return con;
}
//关闭连接
public static void close(Connection con,Statement state,ResultSet rs){
try {
if (rs != null){
rs.close();
}
if (state != null){
state.close();
}
if (con != null){
con.close();;
}
}catch (Exception e){
e.printStackTrace();
}
}
}
新建dao层完成增删改查以adminDao为例:
public class AdminDao {
//添加admin
public Integer addAdmin(Admin admin){
Connection con = SqlServerUtils.getCon();
PreparedStatement ps = null;
Integer result = null;
String sql = "insert into admin values(?,?,?)";
try {
ps = con.prepareStatement(sql);
//设置问号的值
ps.setInt(1,admin.getAdminId());
ps.setString(2,admin.getAdminName());
ps.setString(3,admin.getPwd());
//执行sql语句
int rows = ps.executeUpdate();
if (rows > 0){
return rows;
}else {
return 0;
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
SqlServerUtils.close(con,ps,null);
}
return 0;
}
//删除
public Integer delAdminById(Integer id){
Connection con = SqlServerUtils.getCon();
PreparedStatement ps = null;
ResultSet rs = null;
String sql = "delete from admin where adminid = ? ";
try {
ps = con.prepareStatement(sql);
ps.setInt(1,id);
int rows = ps.executeUpdate();
if (rows > 0){
System.out.println("删除成功");
}else {
System.out.println("删除失败");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
SqlServerUtils.close(con,ps,null);
}
//查找admin
public Admin getAdminByNameAndPwd(String name,String password){
Connection con = SqlServerUtils.getCon();
PreparedStatement ps = null;
ResultSet rs = null;
//String sql = "select * from admin where adminid = '"+id+"'";
String sql = "select * from admin where adminname = ? and password = ?";
try {
ps = con.prepareStatement(sql);
ps.setString(1,name);
ps.setString(2,password);
rs = ps.executeQuery();
if (rs.next()){
int adminId = rs.getInt(1);
String adminName = rs.getString(2);
String pwd = rs.getString(3);
return new Admin(adminId,adminName,pwd);
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
SqlServerUtils.close(con,ps,rs);
}
return null;
}
//查询全部
public List getAdminList(){
Connection con = SqlServerUtils.getCon();
PreparedStatement ps = null;
ResultSet rs = null;
String sql = "select * from admin";
try {
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next()){
int adminId = rs.getInt("adminid");
String adminName = rs.getString("adminName");
String pwd = rs.getString("password");
System.out.println("编号:"+adminId+" 姓名:"+adminName+" 密码:"+pwd);
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
SqlServerUtils.close(con,ps,rs);
}
return null;
}
//修改admin
public Integer updateAdmin(Admin admin){
Connection con = SqlServerUtils.getCon();
PreparedStatement ps = null;
Integer result = null;
String sql = "update admin set adminname = ? , password = ? where adminid = ?";
try {
ps = con.prepareStatement(sql);
ps.setString(1,admin.getAdminName());
ps.setString(2,admin.getPwd());
ps.setInt(3,admin.getAdminId());
result = ps.executeUpdate();
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
SqlServerUtils.close(con,ps,null);
}
return result;
}
}
新建测试类进行测试:
public class sqlServiceTest {
public static void main(String[] args) {
//getAll();
// Admin admin = new Admin(3,"里哈哈","133232");
// updateAdmin(admin);
//getAdminByNameAndPwd("孙道恩","111");
delById(3);
}
//添加数据
public static void addAdmin(){
Admin admin = new Admin(3,"浮动","8989");
AdminDao adminDao = new AdminDao();
Integer rows = adminDao.addAdmin(admin);
if (rows > 0){
System.out.println("添加成功");
}else {
System.out.println("添加失败");
}
}
//单个查询
public static void getAdminByNameAndPwd(String name,String pwd){
AdminDao adminDao = new AdminDao();
Admin adminByNameAndPwd = adminDao.getAdminByNameAndPwd(name, pwd);
System.out.println(adminByNameAndPwd);
}
//查询全部
public static void getAll(){
AdminDao adminDao = new AdminDao();
List adminList = adminDao.getAdminList();
}
//修改信息
public static void updateAdmin(Admin admin){
Integer rows = new AdminDao().updateAdmin(admin);
if (rows > 0){
System.out.println("修改成功");
}else {
System.out.println("修改失败");
}
}
//根据id删除
public static void delById(Integer id){
AdminDao adminDao = new AdminDao();
adminDao.delAdminById(id);
}
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class OracleUtils{
public static final String URL = "jdbc:oracle:thin:@127.0.0.1:1521/PDBORCL";
//后面的PDBORCl是要操作的pdb
//在navicate里面使用select name,open_mode from v$pdbs;查询全部找到这个pdb
//然后在执行下面的语句让此pdb打开alter pluggable database PDBORCL open;
public static final String USER = "c##sde2";
public static final String PASSWORD = "orcl";
public static Connection getConnection(){
//加载驱动
try {
Class.forName("oracle.jdbc.OracleDriver");
}catch (ClassNotFoundException e){
e.printStackTrace();
}
//连接数据库
Connection con = null;
try {
con = DriverManager.getConnection(URL,USER,PASSWORD);
}catch (SQLException e){
e.printStackTrace();
}
System.out.println("连接成功");
return con;
}
}
//关闭连接
public static void close(Connection con, Statement state,ResultSet rs){
if (rs != null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (state != null){
try {
state.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (con != null){
try {
con.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
方式2:
创建一个OracleCon类:
import java.sql.Connection;
import java.sql.DriverManager;
public class OracleCon {
public static Connection getConnection() {
String driver = "oracle.jdbc.driver.OracleDriver";
String url = "jdbc:oracle:thin:@127.0.0.1:1521:ORCLPDB";
String user = "c##daoen"; //用户
String password = "orcl"; //此用户密码
return getConnection(driver, url, user, password);
}
public static Connection getConnection(String driver, String url, String user, String password) {
Connection conn = null;
try {
Class.forName(driver); // 加载数据库驱动
conn = DriverManager.getConnection(url, user, password); // 获取数据库连接
} catch (Exception e) {
System.out.println(e);
}
System.out.println("连接成功");
return conn;
}
}
public class OracleDao {
//查询全部
public List getEmpList(){
Connection con = OracleUtils.getConnection();
Statement state = null;
ResultSet rs = null;
String sql = "select * from c##EMP";
try {
state = con.createStatement();
rs = state.executeQuery(sql);
while (rs.next()){
int empId = rs.getInt(1);
String adminName = rs.getString(2);
String pwd = rs.getString(3);
Date birthday = rs.getDate(4);
System.out.println("编号:"+empId+" 姓名:"+adminName+" 密码"+pwd+" 日期:"+birthday);
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
OracleUtils.close(con,state,rs);
}
return null;
}
//根据姓名和密码查询
public Emp getEmpByNameAndPwd(String userName,String pwd){
Connection con = OracleUtils.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
String sql = "select * from c##EMP where empName = ? and password = ?";
try {
ps = con.prepareStatement(sql);
ps.setString(1,userName);
ps.setString(2,pwd);
rs = ps.executeQuery();
if (rs.next()){
int empId = rs.getInt("empid");
String empName = rs.getString("empname");
String password = rs.getString("password");
Date birthday = rs.getDate("birthday");
System.out.println("编号:"+empId+" 姓名:"+empName+" 密码:"+password+" 日期:"+birthday);
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
OracleUtils.close(con,ps,rs);
}
return null;
}
//删除
public Integer delEmp(Integer id){
Connection con = OracleUtils.getConnection();
PreparedStatement ps = null;
Integer rs = null;
String sql = "delete from c##EMP where empId = ?";
try {
ps = con.prepareStatement(sql);
ps.setInt(1,id);
rs = ps.executeUpdate();
if (rs > 0){
System.out.println("删除成功");
}else {
System.out.println("删除失败");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
OracleUtils.close(con,ps,null);
}
return 0;
}
//添加
public Integer addEmp(Emp emp){
Connection con = OracleUtils.getConnection();
PreparedStatement ps = null;
Integer rs = null;
String sql = "insert into c##EMP values(?,?,?,to_date(?,'yyyy-mm-dd'))";
try {
ps = con.prepareStatement(sql);
ps.setInt(1,emp.getEmpId());
ps.setString(2,emp.getEmpName());
ps.setString(3,emp.getPassword());
java.util.Date date = new java.util.Date(String.valueOf(emp.getBirthday()));
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String time = format.format(date);
ps.setString(4,time);
int rows = ps.executeUpdate();
if (rows > 0){
System.out.println("添加成功");
}else {
System.out.println("添加失败");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
OracleUtils.close(con,ps,null);
}
return 0;
}
//修改
public Integer updateEmp(Emp emp){
Connection con = OracleUtils.getConnection();
PreparedStatement ps = null;
Integer rs = null;
String sql = "update c##EMP set empname = ?,password = ?,birthday = to_date(?,'yyyy-mm-dd') where empId = ?";
try {
ps = con.prepareStatement(sql);
ps.setString(1,emp.getEmpName());
ps.setString(2,emp.getPassword());
java.util.Date date = new java.util.Date(String.valueOf(emp.getBirthday()));
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String time = dateFormat.format(date);
ps.setString(3,time);
ps.setInt(4,emp.getEmpId());
int rows = ps.executeUpdate();
if (rows > 0){
System.out.println("修改成功");
}else {
System.out.println("修改失败");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
OracleUtils.close(con,ps,null);
}
return 0;
}
}
public class OracleTest {
public static void main(String[] args) {
//getEmpByNameAndPwd("孙道恩","111");
// deleteEmpById(2);
// getEmpList();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
// try {
// date = dateFormat.parse("2012-09-12");
// } catch (ParseException e) {
// e.printStackTrace();
// }
// Emp emp = new Emp(5, "理想玩", "23df3", date);
// addEmp(emp);
try {
date = dateFormat.parse("2002-02-04");
} catch (ParseException e) {
e.printStackTrace();
}
Emp emp = new Emp(5, "普罗理想国", "88888888", date);
updateEmp(emp);
}
//查询全部
public static void getEmpList(){
OracleDao oracleDao = new OracleDao();
List empList = oracleDao.getEmpList();
}
//根据名字和密码查询
public static void getEmpByNameAndPwd(String name,String pwd){
OracleDao oracleDao = new OracleDao();
oracleDao.getEmpByNameAndPwd(name, pwd);
}
//根据id删除
public static void deleteEmpById(Integer id){
OracleDao oracleDao = new OracleDao();
oracleDao.delEmp(id);
}
//插入数据
public static void addEmp(Emp emp){
OracleDao oracleDao = new OracleDao();
oracleDao.addEmp(emp);
}
//修改
public static void updateEmp(Emp emp){
OracleDao oracleDao = new OracleDao();
oracleDao.updateEmp(emp);
}
}
public class MysqlUtils {
public static Connection con = null;
public static Statement state = null;
public static ResultSet rs = null;
static {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//连接数据库
public static Connection getCon() {
String url = "jdbc:mysql://localhost:3306/meitao?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false";
String username = "root";
String pwd = "root";
try {
con = DriverManager.getConnection(url, username, pwd);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
System.out.println("连接成功");
return con;
}
//关闭连接
public static void close(Connection con,Statement state,ResultSet rs){
try {
if (rs != null){
rs.close();
}
if (state != null){
state.close();
}
if (con != null){
con.close();;
}
}catch (Exception e){
e.printStackTrace();
}
}
}
public class MysqlAdminDao {
//查询全部
public List getAdminList(){
Connection con = MysqlUtils.getCon();
PreparedStatement ps = null;
ResultSet rs = null;
String sql = "select * from admins";
try {
ps = con.prepareStatement(sql);
ResultSet resultSet = ps.executeQuery();
while (resultSet.next()){
int adminId = resultSet.getInt("adminId");
String adminName = resultSet.getString("adminName");
String pwd = resultSet.getString("pwd");
Date birthday = resultSet.getDate("birthday");
System.out.println("编号:"+adminId+" 姓名:"+adminName+" 密码:"+pwd+"生日:"+birthday);
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
MysqlUtils.close(con,ps,rs);
}
return null;
}
//根据name和密码查询
public Admins getAdminsByIdAndName(String name,String pwd){
Connection con = MysqlUtils.getCon();
PreparedStatement ps= null;
ResultSet rs = null;
String sql = "select * from admins where adminname = ? and pwd = ?";
try {
ps = con.prepareStatement(sql);
ps.setString(1,name);
ps.setString(2,pwd);
ResultSet set = ps.executeQuery();
while (set.next()){
int adminId = set.getInt("adminId");
String adminName = set.getString("adminName");
String password = set.getString("pwd");
Date birthday = set.getDate("birthday");
System.out.println("编号:"+adminId+" 姓名:"+adminName+" 密码:"+password+"生日:"+birthday);
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
MysqlUtils.close(con,ps,rs);
}
return null;
}
//根据id删除
public Integer delAdminById(Integer id){
Connection con = MysqlUtils.getCon();
PreparedStatement ps = null;
ResultSet rs = null;
String sql = "delete from admins where adminid = ?";
try {
ps = con.prepareStatement(sql);
ps.setInt(1,id);
int rows = ps.executeUpdate();
if (rows > 0){
System.out.println("删除成功");
}else {
System.out.println("删除失败");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
MysqlUtils.close(con,ps,rs);
}
return 0;
}
//添加数据
public Integer addAdmins(Admins admins){
Connection con = MysqlUtils.getCon();
PreparedStatement ps = null;
ResultSet rs = null;
String sql = "insert into admins values(?,?,?,?)";
try {
ps = con.prepareStatement(sql);
ps.setInt(1,admins.getAdminId());
ps.setString(2,admins.getAdminName());
ps.setString(3,admins.getPwd());
java.util.Date date = new java.util.Date(String.valueOf(admins.getBirthday()));
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String time = dateFormat.format(date);
ps.setString(4,time);
int rows = ps.executeUpdate();
if (rows > 0){
System.out.println("添加成功");
}else {
System.out.println("添加失败");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
MysqlUtils.close(con,ps,null);
}
return 0;
}
//修改数据
public Integer updateAdmins(Admins admins){
Connection con = MysqlUtils.getCon();
PreparedStatement ps = null;
ResultSet rs = null;
String sql = "update admins set adminname = ?,pwd = ?,birthday = ? where adminid = ?";
try {
ps = con.prepareStatement(sql);
ps.setString(1,admins.getAdminName());
ps.setString(2,admins.getPwd());
java.util.Date date = new java.util.Date(String.valueOf(admins.getBirthday()));
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String time = dateFormat.format(date);
ps.setString(3,time);
ps.setInt(4,admins.getAdminId());
int rows = ps.executeUpdate();
if (rows > 0){
System.out.println("修改成功");
}else {
System.out.println("修改失败");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
MysqlUtils.close(con,ps,null);
}
return 0;
}
}
public class MysqlTest {
public static void main(String[] args) {
// getList();
// getAdminsByNameAndPwd("孙道恩","666");
// deleteById(3);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = dateFormat.parse("2015-02-04");
} catch (ParseException e) {
e.printStackTrace();
}
Admins admins = new Admins(3,"小金刚","sfd434",date);
//addAdmins(admins);
updateAdmins(admins);
}
//查找全部
public static void getList(){
MysqlAdminDao mysqlAdminDao = new MysqlAdminDao();
mysqlAdminDao.getAdminList();
}
//感觉name和pwd查找
public static void getAdminsByNameAndPwd(String name,String pwd){
MysqlAdminDao mysqlAdminDao = new MysqlAdminDao();
mysqlAdminDao.getAdminsByIdAndName(name, pwd);
}
//单个删除
public static void deleteById(Integer id){
MysqlAdminDao mysqlAdminDao = new MysqlAdminDao();
mysqlAdminDao.delAdminById(id);
}
//添加数据
public static void addAdmins(Admins admins){
MysqlAdminDao mysqlAdminDao = new MysqlAdminDao();
mysqlAdminDao.addAdmins(admins);
}
//修改数据
public static void updateAdmins(Admins admins){
MysqlAdminDao mysqlAdminDao = new MysqlAdminDao();
mysqlAdminDao.updateAdmins(admins);
}
}
/**
* 分页Bean
*
* @author sde
*/
public class PagerUtil {
/**
* 当前页码数
*/
private int currentPage = 1;
/**
* 每页显示记录条数, 默认为 2
*/
private int sizePerPage = 2;
/**
* 总页数
*/
private int totalPage;
/**
* 需要分页的长字符串
*/
@SuppressWarnings("unchecked")
private List topicSelect;
public PagerUtil() {
}
/**
* 返回当前页的文本
*
* @return
*/
@SuppressWarnings("unchecked")
public List getCurrentPagedText() {
try {
if (getCurrentPage() < getTotalPage()) {
return getTopicSelect().subList(
(getCurrentPage() - 1) * getSizePerPage(), getCurrentPage() * getSizePerPage());
} else if (getTotalPage() > 0) {
return getTopicSelect().subList((getCurrentPage() - 1) * getSizePerPage(), getTopicSelect().size());
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* @return Returns the 当前页码数.
*/
public int getCurrentPage() {
if (currentPage <= 0)
currentPage = 1;
return currentPage;
}
/**
* 设置当前页码, 从 1 开始.
*
* @param currentPage The 当前页码数 to set.
*/
public void setCurrentPage(int currentPage) {
if (currentPage <= 0) {
currentPage = 1;
}
this.currentPage = currentPage;
}
/**
* @return Returns the 总页码数, 如果没有数据, 就返回 1.
*/
public int getTotalPage() {
if (getTopicSelect() == null)
totalPage = 0;
totalPage = (int) Math.ceil(1.0 * getTopicSelect().size()
/ getSizePerPage()); // 总页面数
if (totalPage == 0)
totalPage = 1;
return totalPage;
}
/**
* @param totalPage The totalPage to set.
*/
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
/**
* @return Returns the 每页显示行数.
*/
public int getSizePerPage() {
return sizePerPage;
}
/**
* @param sizePerPage The 每页显示行数to set.
*/
public void setSizePerPage(int sizePerPage) {
this.sizePerPage = sizePerPage;
}
/**
* @return Returns the 需要分页的文本.
*/
@SuppressWarnings("unchecked")
public List getTopicSelect() {
return topicSelect;
}
@SuppressWarnings("unchecked")
public void setTopicSelect(List topicSelect) {
this.topicSelect = topicSelect;
}
}
case "pageList":
//当前是第几页
int currentPage = 1;
//判断当前页码是否为空
if (req.getParameter("currentPage") != null){
//不为空在页面中用户在请求分页
currentPage = Integer.parseInt(req.getParameter("currentPage"));
}
//一共多少页
int maxPage;
List list = employeesService.getList();
System.out.println(list);
//创建分页对象
PagerUtil pager = new PagerUtil();
//需要分页的文本
pager.setTopicSelect(list);
//设置每行显示的行数
pager.setSizePerPage(3);
//获取最大页数
maxPage = pager.getTotalPage();
//获取当前页
pager.setCurrentPage(currentPage);
//存值
System.out.println(pager.toString());
req.setAttribute("lists",pager);
req.getRequestDispatcher("list.jsp").forward(req,resp);
break;
${user.empId}
${user.empName}
${user.birthday}
${user.address}
${user.tel}
${user.deptName}
删除
修改
首页
上一页
下一页
末页
每页显示 ${lists.sizePerPage} 条
第 ${lists.currentPage} 页
共 ${lists.totalPage} 页