首页 > 代码库 > JDBC的连接和增删改和查找

JDBC的连接和增删改和查找

package Test2;


import java.sql.*;
import java.sql.DriverManager;
import java.sql.SQLException;


public class DB {
private static String driver="com.microsoft.sqlserver.jdbc.SQLServerDriver";
private static String url="jdbc:sqlserver://localhost:1433;database=stuDB";
private static String use="sa";
private static String pwd="123456";
private static Connection  con;

public static Connection getcon()
{
try {
Class.forName(driver);
con=DriverManager.getConnection(url,use,pwd);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


return con;

}
public static void CloseAll(ResultSet re,Statement sta,Connection con)

{
try {
if(re!=null)
{
re.close();
}
if(sta!=null)
{
sta.close();
}
if(con!=null)
{
con.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}



}


}

----------------------------------

package Test2;


import java.sql.*;
import java.util.*;


public class StuDB {
private Connection con=null;
private PreparedStatement sta=null;
private ResultSet re=null;
int result=0;

public int updateSet(String sql,List l)
{
try {
con=DB.getcon();
sta=con.prepareStatement(sql);
for(int i=0;i<l.size();i++)
{
sta.setObject(i+1, l.get(i));
}
result=sta.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return result;



}
public List<Student> find(String sql)
{
List <Student> l=new ArrayList<Student>();
try {
con=DB.getcon();
sta=con.prepareStatement(sql);
re=sta.executeQuery();
while(re.next())
{
String id=re.getString(1);
String name=re.getString(2);
String sex=re.getString(3);
Student si=new Student(id,name,sex);
l.add(si);

}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return l;

}



}

---------------------------

package Test2;


import java.util.*;


public class Test {
public static void main(String[] args) {
StuDB s=new StuDB();
List l=new ArrayList();
String sql="delete from useinfo where id=?";
l.add(1);

int re=s.updateSet(sql, l);
if(re>0)
{
System.out.println("000cc");
}
String sql2="select *from useinfo";
List<Student> l2=s.find(sql2);
for(Student st:l2)
{
System.out.println(st.getId()+st.getName()+st.getSex());
}
}


}

 

JDBC的连接和增删改和查找