Java 连接 SqlServer工具类
1.下载 server2008R2驱动jar包
http://www.microsoft.com/zh-cn/download/confirmation.aspx?id=21599
2.代码实现
1)实体:
package entity; import java.io.Serializable;
import java.util.Date; public class User implements Serializable{
private int id;
private String username;
private String password;
private Date createtime;
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 String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Date getCreatetime() {
return createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
public User(int id, String username, String password, Date createtime) {
super();
this.id = id;
this.username = username;
this.password = password;
this.createtime = createtime;
} public User(String username, String password, Date createtime) {
super();
this.username = username;
this.password = password;
this.createtime = createtime;
}
public User() {
super(); }
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", password="
+ password + ", createtime=" + createtime + "]";
} }
2.dao
package dao; import java.util.List; import entity.User; public interface UserDao {
public void add(User u); public User getByUsername(String username); public void update(User u); public void delete(String username); public List<User> findAll();
}
3.ImplDao
package daoImpl; import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Date; import java.util.List; import jdbcutil.JdbcUtil;
import dao.UserDao;
import entity.User; public class UserDaoImpl implements UserDao { @Override
public void add(User u) { Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null; try {
con = JdbcUtil.getConnection();
String sql = "insert into [user](username,password,createtime) values(?,?,?)";
stmt= con.prepareStatement(sql);
stmt.setString(1, "test");
stmt.setString(2,"123456");
stmt.setDate(3, new java.sql.Date(u.getCreatetime().getTime()));
stmt.executeUpdate(); } catch (Exception e) { e.printStackTrace();
}finally
{
JdbcUtil.close(rs, stmt, con);
} } @Override
public User getByUsername(String username) { Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null; try {
con = JdbcUtil.getConnection();
String sql = "select * from [user] where username=?";
stmt = con.prepareStatement(sql);
stmt.setString(1, username);
rs = stmt.executeQuery();
while(rs.next())
{
int id = rs.getInt("id");
String name = rs.getString("username");
String password = rs.getString("password");
Date time = rs.getDate("createtime"); User u = new User(id,username,password,time); return u; }
} catch (Exception e) { e.printStackTrace();
}
finally
{ JdbcUtil.close(rs, stmt, con);
}
return null;
} @Override
public void update(User u) { Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null; try {
con = JdbcUtil.getConnection(); String sql = "update [user] set password=? where username=?"; stmt = con.prepareStatement(sql); stmt.setString(1, u.getPassword()); stmt.setString(2, u.getUsername()); stmt.executeUpdate(); } catch (Exception e) { e.printStackTrace();
}
finally
{ JdbcUtil.close(rs, stmt, con);
}
} @Override
public void delete(String username) { Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null; try {
con = JdbcUtil.getConnection(); String sql = "delete from [user] where username=?"; stmt = con.prepareStatement(sql); stmt.setString(1,username); stmt.executeUpdate(); } catch (Exception e) { e.printStackTrace();
}
finally
{ JdbcUtil.close(rs, stmt, con);
}
} @Override
public List<User> findAll() {
List<User> list = new ArrayList<User>(); Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null; try {
con = JdbcUtil.getConnection();
String sql = "select * from [user]"; stmt = con.prepareStatement(sql); rs = stmt.executeQuery(); while(rs.next())
{
User u = new User(rs.getInt("id"), rs.getString("username"),rs.getString("password"),rs.getDate("createtime"));
list.add(u); }
return list; } catch (Exception e) { e.printStackTrace();
}
finally
{
JdbcUtil.close(rs, stmt, con); } return null;
} }
4.JDBC工具类
package jdbcutil; import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties; public class JdbcUtil { private static String className;
private static String url;
private static String user;
private static String password; static
{ try {
InputStream in = JdbcUtil.class.getClassLoader().getResourceAsStream("dbinfo.properties"); Properties props = new Properties();
props.load(in); className = props.getProperty("className"); url = props.getProperty("url"); user = props.getProperty("user"); password = props.getProperty("password"); //System.out.println(className); //System.out.println(url); //注册驱动
Class.forName(className); } catch (Exception e) { e.printStackTrace();
} } public static Connection getConnection() throws Exception
{
return DriverManager.getConnection(url, user, password); } public static void close(ResultSet rs, Statement stmt,Connection con)
{ if(rs!=null)
{
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} rs= null;
} if(stmt!=null)
{
try {
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} stmt= null;
} if(con!=null)
{
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} con= null;
}
}
}
5.用于测试SQLServer驱动是否正确
package test; import java.sql.Connection;
import java.sql.DriverManager; public class JdbcTest {
public static void test()
{
Connection conn = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); //注意url中没有microsoft才能使用,网上增加了microsoft的会出现No suitable driver found for//jdbc:microsoft:sqlserver:……的错误
//若安装多个实例时,要确认相应的port及实例名
String url="jdbc:sqlserver://localhost:1433;DatabaseName=JavaTestDB";
String user="sa";
String password="123456";
conn= DriverManager.getConnection(url,user,password); System.out.println("链接成功"); } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
if(conn!=null)
{
try {
conn.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} conn = null; } } }
}
备注: dbinfo.properties文件:
6.添加SQLServer jar包
Java 连接 SqlServer工具类的更多相关文章
- python连接sqlserver工具类
上代码: # -*- coding:utf-8 -*- import pymssql import pandas as pd class MSSQL(object): def __init__(sel ...
- HttpTool.java(在java tool util工具类中已存在) 暂保留
HttpTool.java 该类为java源生态的http 请求工具,不依赖第三方jar包 ,即插即用. package kingtool; import java.io.BufferedReader ...
- Java基础-DButils工具类(QueryRunner)详解
Java基础-DButils工具类(QueryRunner)详解 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 如果只使用JDBC进行开发,我们会发现冗余代码过多,为了简化JDBC ...
- java 邮件发送工具类【来源网络自己已经实际应用】
最近在做一个Java发送邮件的工具类,现在分享一下完整的代码 首先需要java邮件的包javax.mail-1.5.4.jar 之前因为链接给错了,很不好意思,现在重新发一次. 包在这里可以下载htt ...
- Java操作Redis工具类
依赖 jar 包 <dependency> <groupId>redis.clients</groupId> <artifactId>jedis< ...
- Druid连接池工具类
package cn.zmh.PingCe; import com.alibaba.druid.pool.DruidDataSourceFactory; import javax.sql.DataSo ...
- Android OkHttp网络连接封装工具类
package com.lidong.demo.utils; import android.os.Handler; import android.os.Looper; import com.googl ...
- 基于SqlClient开发SQLServer工具类 伸手党的福音
注意:代码直接Copy调用即可,SQLServer工具类跟我上一个Oracle工具类有所不同,区别在于调用存储过程中时参数的使用,无需输入对应的存储游标名称 特点:根据用户传入的参数类型来识别存储中对 ...
- java文件处理工具类
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedRead ...
随机推荐
- JavaScript从入门到精通
第一(基本语法) if(condition1){ expression1; }else if(condition2){ expression2; }else{ expression3; } switc ...
- Assign the task HDU - 3974(dfs序+线段树)
There is a company that has N employees(numbered from 1 to N),every employee in the company has a im ...
- MT【8】和e有关的一个极限
解答: 评:这里涉及到e有关的极限的单调性,求导数得:
- bzoj2142: 礼物
2142: 礼物 Description 一年一度的圣诞节快要来到了.每年的圣诞节小E都会收到许多礼物,当然他也会送出许多礼物.不同的人物在小E心目中的重要性不同,在小E心中分量越重的人,收到的礼物会 ...
- 【Luogu4630】【APIO2018】 Duathlon 铁人两项 (圆方树)
Description 给你一张\(~n~\)个点\(~m~\)条边的无向图,求有多少个三元组\(~(x, ~y, ~z)~\)满足存在一条从\(~x~\)到\(~z~\)并且经过\(~y~\)的 ...
- 【AGC016E】Poor Turkeys
Description 有\(n\)(\(1 \le n \le 400\))只鸡,接下来按顺序进行\(m\)(\(1 \le m \le 10^5\))次操作.每次操作涉及两只鸡,如果都存在则随意拿 ...
- 【洛谷P4113】采花 HH的项链+
题目大意:静态统计序列区间中出现次数大于等于 2 的颜色数. 题解:类似于HH的项链,只需将 i 和 pre[i] 的关系对应到 pre[i] 和 pre[pre[i]] 的关系即可. 代码如下 #i ...
- VUE在BODY上绑定enter事件
mounted () { this.bodyListener = (e) => { if (e.keyCode === 13 && e.target === document.b ...
- 初探ant-design(web版本二)
Dropdown下拉菜单 向下弹出的列表. 何时使用# 当页面上的操作命令过多时,用此组件可以收纳操作元素.点击或移入触点,会出现一个下拉菜单.可在列表中进行选择,并执行相应的命令. 最简单的下拉菜单 ...
- 2018 ACM 网络选拔赛 焦作赛区
A. Magic Mirror #include <cstdio> #include <cstdlib> #include <cmath> #include < ...