package hy;
import java.sql.*;
public class DB {
private Connection con = null;
private String classname = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
private String url = "jdbc:sqlserver://localhost:1433;DatabaseName=ZSB";
public DB(){
}
public Connection getCon(){
try{
Class.forName(classname);
}catch(ClassNotFoundException e){
e.printStackTrace();
}
try{
con=DriverManager.getConnection(url, "sa", "");
System.out.println("数据库连接成功!");
}catch(Exception e){
e.printStackTrace(System.err);
con=null;
}
return con;
}
public void closed(){
try{
if(con!=null)con.close();
}catch(SQLException e){
e.printStackTrace();
}
}
public static void main(String [] args){
}
}
package hy;
import java.sql.*;
public class DBOperate extends DB{
private Connection conn=null;
private Statement stm = null;
private ResultSet rs = null;
public DBOperate(){
}
public int exeQuery(String str){
int success = 0;
try{
if(conn==null){
conn = super.getCon();
}
stm = conn.createStatement();
success = stm.executeUpdate(str);
}catch(SQLException e){
e.printStackTrace();
success = 0;
}
return success;
}
public ResultSet openQuery(String str){
try{
if(conn==null){
conn = super.getCon();
}
Statement stm = conn.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY );
rs = stm.executeQuery(str);
}catch(SQLException e){
e.printStackTrace();
rs = null;
}
return rs;
}
public static void main(String [] args){
DBOperate db = new DBOperate();
ResultSet rs=db.openQuery("select *from download");
try{
int id=1;
while(rs.next()){
int t=rs.getInt("id");
if(t==id){
id++;
}
}
System.out.println(id);
}catch(SQLException e){
e.printStackTrace();
}
}
}
java连接数据库
最新推荐文章于 2019-07-23 07:24:01 发布