package DB;
import java.sql.*;
import java.util.*;
public class dbop
{
public final static StringDriverName = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
public static String url =null;
public static String username =null;
public static String password =null;
public dbop(String usernamepame,StringPasswordpame,String urlpame)
{
super();
username = usernamepame;
password = Passwordpame;
url = urlpame;
}
/**
* @创建数据库的连接
* @return 返回conn
*/
public static Connection getConnection()
{
Connection conn = null;
try
{
Class.forName(DriverName).newInstance();//实例化数据库驱动
conn =DriverManager.getConnection(url,username,password);//连接数据库
System.out.print("连接数据库成功!");
}
catch (InstantiationException e)
{
System.out.println("驱动实例化失败!");
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
catch (ClassNotFoundException e)
{
System.out.println("加载类时发生异常!");
e.printStackTrace();
}
catch (SQLException e)
{
System.out.println("数据库连接异常!");
e.printStackTrace();
}
return conn;
}
/**
*@创建数据库查询语句并执行
*@return 返回ArrayList查询结果
*/
public static ArrayList query(String SQL)
{
ArrayList arrayList =null;
Connection conn = null;
conn = getConnection();
try
{
Statement stmt =conn.createStatement();//创建数据库查询语句
ResultSet rs =stmt.executeQuery(SQL);//执行查询语句并返回rs
int colnum =rs.getMetaData().getColumnCount();//记录返回表的列数
if(rs!=null&&colnum!=0)//查询结果不为空
{
arrayList = newArrayList();
ArrayList tempAR = newArrayList();
while(rs.next())
{
for(int i =0;i <= colnum;i++)
{
tempAR.add(rs.getObject(i));
}
arrayList.add(tempAR);
}
}
else
{
System.out.print("查询结果为空");//查询结果为空
}
conn.close();
stmt.close();
rs.close();
}
catch(SQLException e)
{
System.out.print("查询失败!");
e.printStackTrace();
}
return arrayList;
}
/**
* @数据库查更新和删除操作
* @return 返回所影响的行数
*/
public static intupdata(String updataSQL)
{
int rownum =0;
try
{
Connection conn = getConnection();
Statement stmt = conn.createStatement();
rownum = stmt.executeUpdate(updataSQL);
conn.close();
stmt.close();
}
catch(SQLException e)
{
System.out.print("数据库更新或删除操作时,创建执行语句失败!");
e.printStackTrace();
}
return rownum;
}
}
本类只适用与SQLserver2000,经测试通过!