首页 > 代码库 > DAO实现查询
DAO实现查询
package DB3;
import java.sql.*;
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 get()
{
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 st,Connection con)
{
try {
if(re!=null)
{
re.close();
}
if(st!=null)
{
st.close();
}
if(con!=null)
{
con.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static int executeUpdate(String sql,Object [] par)
{
int result=0;
Connection con=null;
PreparedStatement sta=null;
try {
con=get();
sta=con.prepareStatement(sql);
setUpdate(sta,par);
result=sta.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
private static void setUpdate(PreparedStatement sta, Object[] par) {
// TODO Auto-generated method stub
if(par==null)return;
try {
for(int i=0;i<par.length;i++)
{
sta.setObject(i+1, par[i]);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
-----------------------------------
package DB3;
import java.util.*;
public interface StuDAO {
public int insertInfo(Student stu);
public int updateInfo(Student stu);
public int deleteInfo(Student stu);
public List<Student > queryInfo();
}
------------------------
package DB3;
import java.util.List;
public class StuDAOImple extends DB implements StuDAO{
@Override
public int deleteInfo(Student stu) {
// TODO Auto-generated method stub
return 0;
}
@Override
public int insertInfo(Student stu) {
// TODO Auto-generated method stub
int result=0;
String sql="insert useinfos values (?,?)";
Object [] par={stu.getName(),stu.getSex()};
result=super.executeUpdate(sql, par);
return result;
}
@Override
public List<Student> queryInfo() {
// TODO Auto-generated method stub
return null;
}
@Override
public int updateInfo(Student stu) {
// TODO Auto-generated method stub
return 0;
}
}
-------------------------------
package DB3;
public class Test {
public static void main(String[] args) {
StuDAO st=new StuDAOImple();
Student stu=new Student("刘瑞光","男");
st.insertInfo(stu);
System.out.println("成功");
}
}
DAO实现查询