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 ...
随机推荐
- ACM数论之旅12---康托展开((*゚▽゚*)装甲展开,主推进器启动,倒计时3,2,1......)
在我们做题中,搜索也好,动态规划也好,我们往往有时候需要用一个数字表示一种状态 比如有8个灯泡排成一排,如果你用0和1表示灯泡的发光情况 那么一排灯泡就可以转换为一个二进制数字了 比如 0110011 ...
- hive存储、数据模型、内部表
创建内部表 加一列元素 删除表
- Pandas三个数据结构
系列(Series) 数据帧(DataFrame) 面板(Panel) 这些数据结构构建在Numpy数组之上,这意味着它们很快. 考虑这些数据结构的最好方法是,较高维数据结构是其较低维数据结构的容器. ...
- mysql 性能指标
qps 每秒处理的查询数tps 每秒处理的事务数IOPS 每秒磁盘进行的I/O操作次数 一.TPS:Transactions Per Second(每秒传输的事物处理个数),即服务器每秒处理的事务数. ...
- BZOJ3862Little Devil I——树链剖分+线段树
题目大意: 给一棵树,每条边可能是黑色或白色(起始都是白色),有三种操作: 1.将u到v路径上所有边颜色翻转(黑->白,白->黑) 2.将只有一个点在u到v路径上的边颜色翻转 3.查询u到 ...
- java项目http变更https
1. 创建 keystore 文件 执行keytool -genkey -v -alias tomcat -keyalg RSA -validity 3650 -keystore c:\tomc ...
- ubuntu 18.04 使用 nvm 安装 nodejs
20190315 使用 nvm 安装 nodejs 1. 找到 nvm 官网帮助 https://github.com/creationix/nvm 我习惯于 terminal 操作,所以选择 git ...
- 对 spi 的认知
在使用 SPI 外设场景下,只需将数据送至 SPI->DR,外设将数据自动发走 在使用 DMA 外设场景下,只需指定数据缓存区地址及 SPI->DR 地址,这样就无需劳驾 CPU 而开始数 ...
- Python进制表示及转换
进制表示: 二进制:>>> abin = 0b1000>>> abin8 八进制:>>> aoct = 0o123 (数字0,字母o)>&g ...
- 拆分string 用空格 逗号
string that have both comma and space struct tokens: std::ctype<char>{ tokens(): std::ctype< ...