编写一个java程序,通过jdbc访问数据库实现对数据库的插入,删除,修改和查询操作

java

我刚写了一个只有插入的,望采纳
import java.sql.*;
import java.util.*;
public class TestPre {
public static void main(String[] args) {
int i=0,deptno=0;//i只做while循环使用,deptno是表dept2中的一个属性,类型是int
String dname=null,loc=null;//dname和loc也是表dept2的属性,类型是String
Scanner s=new Scanner(System.in);
System.out.println("请输入3个参数");
while(i<3){
try{
deptno=s.nextInt();
i++;
dname=s.next();
i++;
loc=s.next();
i++;
}catch(InputMismatchException e){
System.out.println("输入的类型不符,退出");
System.exit(-1);
}
}
Connection conn=null;
PreparedStatement pstmt=null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/mydata?"+ "user=root&password=root");
pstmt=conn.prepareStatement("insert into dept2 values(?,?,?)");
pstmt.setInt(1, deptno);
pstmt.setString(2, dname);
pstmt.setString(3, loc);
pstmt.executeUpdate();
System.out.println("插入完成");
} catch (ClassNotFoundException e) {
System.out.println("连接数据库不成功,程序退出");
System.exit(-1);
} catch (SQLException e) {
System.out.println("连接数据库不成功,程序退出");
System.exit(-1);
}
finally{
try{
if(pstmt!=null){
pstmt.close();
pstmt=null;
}
if(conn!=null){
conn.close();
conn=null;
}
}catch(SQLException e){
e.printStackTrace();
}
}
}
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-02-13
增删改查。。是做程序最简单的东西。。。楼主还是自己动手啊。。。。
第2个回答  推荐于2018-01-08
1.增加
String s1="insert into tableNames (id,name,password) values(myseq.nextval,?,?);"
Class.forName(driver);
Connection conn = DriverManager.getConnection(url,dbUser,dbPwd);
PreparedStatement prepStmt = conn.prepareStatement(s1);
prepStmt.setString(1,name);
prepStmt.setString(2,password);
ResultSet rs=stmt.executeUpdate();
2、删除
String s2="delete from tbNames where name=?";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url,dbUser,dbPwd);
PreparedStatement prepStmt = conn.prepareStatement(s2);
prepStmt.setString(1,name);
ResultSet rs=stmt.executeUpdate();
3、修改
String s3=“update tbNames set name=? where id=?”;
Class.forName(driver);
Connection conn = DriverManager.getConnection(url,dbUser,dbPwd);
PreparedStatement prepStmt = conn.prepareStatement(s3);
prepStmt.setString(1,name);
prepStmt.setString(2,id);
ResultSet rs=stmt.executeUpdate();
4、查询
String s4="select id,name,password from tbNames";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url,dbUser,dbPwd);
Statement stmt=conn.createStatement();
ResultSet rs = stmt.executeQuery(s4);
while(rs.next){
int id=rs.getInt(1);
String name = rs.getString(2);
String pwd=rs.getString(3);
System.out.println(id+name+pwd); }

以上四步必须都得关闭连接;!!!
rs.close();
stmt.close();
conn.close();本回答被网友采纳
第3个回答  2012-02-10
增删改查 这是最基本的。 劝楼主还是自己动手写写。