MySQL与Myeclipse数据库的链接操作:
添加修改等一系列操作:
public List queryuser(String name,String pwd){
JdbcUtil jc=new JdbcUtil();
List list=new ArrayList();
Connection conn=jc.getConn();
PreparedStatement ps=null;
ResultSet rs=null;
String sql=“SELECT * FROM "
+ “userinfo where userName=’”+name+”’ and userPassword=’"+pwd+"’ ";
try {
ps=conn.prepareStatement(sql);
rs=ps.executeQuery();
while(rs.next()){
list.add(new UserInfo(rs.getInt(“userid”),rs.getString(“username”),rs.getString(“userid”)));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
jc.closeSql(rs, ps, conn);
}
return list;
}
public List<UserInfo> queryAll(){
List<UserInfo> list=new ArrayList<UserInfo>();
JdbcUtil jc=new JdbcUtil();
Connection conn=jc.getConn();
PreparedStatement ps=null;
ResultSet rs=null;
String sql="select * from userinfo";
try {
ps=conn.prepareCall(sql);
rs=ps.executeQuery();
while(rs.next()){
list.add(new UserInfo(rs.getInt("userId"),
rs.getString("username"),
rs.getString("userPassword")));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
jc.closeSql(rs, ps, conn);
}
return list;
}
public void inertDb(UserInfo userEnt){
JdbcUtil jc=new JdbcUtil();
Connection conn=jc.getConn();
PreparedStatement ps=null;
String sql="insert into userinfo(userId,userName,userPassword) values(?,?,?)";
try {
ps=conn.prepareStatement(sql);
ps.setInt(1, userEnt.getUserId());
ps.setString(2, userEnt.getUserName());
ps.setString(3, userEnt.getUserPassword());
int i=ps.executeUpdate();
if(i>0){
System.out.println("添加成功");
}else {
System.out.println("添加失败");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
jc.closeSql(null, ps, conn);
}
}
public void updateDb(UserInfo userEnt){
JdbcUtil jc=new JdbcUtil();
Connection conn=jc.getConn();
PreparedStatement ps=null;
String sql=“update userinfo set userName=?,userPassword=? where userId=?”;
try {
ps=conn.prepareStatement(sql);
ps.setString(1, userEnt.getUserName());
ps.setInt(2, userEnt.getUserId());
ps.setString(3, userEnt.getUserPassword());
int i=ps.executeUpdate();
if(i>0){
System.out.println(“修改成功”);
}else {
System.out.println(“修改失败”);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
jc.closeSql(null, ps, conn);
}
}
public void deleteDb(UserInfo userEnt){
JdbcUtil jc=new JdbcUtil();
Connection conn=jc.getConn();
PreparedStatement ps=null;
String sql=“delete from userinfo where userName=?”;
try {
ps=conn.prepareStatement(sql);
ps.setString(1, userEnt.getUserName());
int i=ps.executeUpdate();
if(i>0){
System.out.println(“删除成功”);
}else {
System.out.println(“删除失败”);
}