数据库连接类
package sqlServer;
import java.sql.Connection;
import java.sql.DriverManager;
/**
* 数据库连接类
*
* @author Administrator
*
*/
public class DBConnection {
// 加载并连接本地的SQLServer
String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String dbURL = "jdbc:sqlserver://1.1.2.2:1433;DatabaseName=testImage;"; // "USCSecondhandMarketDB"是数据库名称
String userName = "test"; // 用户名
String pwd = "456"; // 密码
/**
* 创建时加载驱动
*/
public DBConnection() {
try {
Class.forName(driverName);
} catch (Exception e) {
System.err.println("驱动加载失败");
}
}
public Connection getConnection() {
Connection con = null;
try {
con = DriverManager.getConnection(dbURL, userName, pwd);
System.err.println("数据库连接成功");
} catch (Exception e) {
e.printStackTrace();
}
return con;
}
}
对数据的操作
package sqlServer;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import entity.Entity;
/**
* 对数据的操作
*/
public class Dao {
DBConnection dbCon = null;
Connection connection = null;
PreparedStatement state = null;// 预编译的sql语句对象
String sql = null;// sql语句
/**
* 创建用户操作类时加载驱动
*/
public Dao() {
dbCon = new DBConnection();
}
/**
* 批量添加到sqlserver
*/
public void add(ArrayList<Entity> list){
connection=dbCon.getConnection();
sql="insert into image values(?,?)";
try{
connection.setAutoCommit(false);
state=connection.prepareStatement(sql);
for(int i = 0;i<list.size();i++){
state.setString(1, list.get(i).getId());
state.setString(2, list.get(i).getImage());
state.addBatch();
}
state.executeBatch();
connection.commit();
System.err.println("数据批量插入sqlserver成功");
state.close();
}catch(Exception e){
System.err.println("数据插入sqlserver失败");
e.printStackTrace();
}finally{
if(connection!=null){
try{
connection.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
/**
* 根据ID查找图片
* @param ID
*/
public Entity getImageList(String id){
Entity entity = new Entity();
connection=dbCon.getConnection();
sql="select * from image where id=?";
try{
state=connection.prepareStatement(sql);
state.setString(1, id);
ResultSet set=state.executeQuery();
while(set.next()){
entity.id = set.getString("id").trim();
entity.image = set.getString("image").trim();
}
state.close();
set.close();
System.err.println("从sqlserver中查找成功");
}catch(Exception e){
System.err.println("从sqlserver中查找失败");
}finally{
if(connection!=null){
try{
connection.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
return entity;
}
}
本文介绍了一个用于连接和操作SQLServer数据库的Java类。包括数据库连接类DBConnection的实现,以及进行数据批量添加和根据ID查找图片的具体操作。

3000

被折叠的 条评论
为什么被折叠?



