怎样编写一个java程序能通过jdbc访问数据库实现对数据库的插入、删除、修改和查询?

怎样编写一个java程序能通过jdbc访问数据库实现对数据库的插入、删除、修改和查询?,第1张

1.增加\x0d\x0aString s1="insert into tableNames (id,name,password) values(myseq.nextval,?,?)"\x0d\x0aClass.forName(driver)\x0d\x0aConnection conn = DriverManager.getConnection(url,dbUser,dbPwd)\x0d\x0aPreparedStatement prepStmt = conn.prepareStatement(s1)\x0d\x0aprepStmt.setString(1,name)\x0d\x0aprepStmt.setString(2,password)\x0d\x0aResultSet rs=stmt.executeUpdate()\x0d\x0a2、删除\x0d\x0aString s2="delete from tbNames where name=?"\x0d\x0aClass.forName(driver)\x0d\x0aConnection conn = DriverManager.getConnection(url,dbUser,dbPwd)\x0d\x0aPreparedStatement prepStmt = conn.prepareStatement(s2)\x0d\x0aprepStmt.setString(1,name)\x0d\x0aResultSet rs=stmt.executeUpdate()\x0d\x0a3、修改\x0d\x0aString s3=“update tbNames set name=? where id=?”\x0d\x0aClass.forName(driver)\x0d\x0aConnection conn = DriverManager.getConnection(url,dbUser,dbPwd)\x0d\x0aPreparedStatement prepStmt = conn.prepareStatement(s3)\x0d\x0aprepStmt.setString(1,name)\x0d\x0aprepStmt.setString(2,id)\x0d\x0aResultSet rs=stmt.executeUpdate()\x0d\x0a4、查询\x0d\x0aString s4="select id,name,password from tbNames"\x0d\x0aClass.forName(driver)\x0d\x0aConnection conn = DriverManager.getConnection(url,dbUser,dbPwd)\x0d\x0aStatement stmt=conn.createStatement()\x0d\x0aResultSet rs = stmt.executeQuery(s4)\x0d\x0awhile(rs.next){\x0d\x0aint id=rs.getInt(1)\x0d\x0aString name = rs.getString(2)\x0d\x0aString pwd=rs.getString(3)\x0d\x0aSystem.out.println(id+name+pwd)} \x0d\x0a\x0d\x0a以上四步必须都得关闭连接;!!!\x0d\x0ars.close()\x0d\x0astmt.close()\x0d\x0aconn.close()

我刚写了一个只有插入的,望采纳

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()

}

}

}

}


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/sjk/9367844.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-27
下一篇 2023-04-27

发表评论

登录后才能评论

评论列表(0条)

保存