其他分享
首页 > 其他分享> > 2021-04-06

2021-04-06

作者:互联网

Java图形化界面访问数据库技术

一、实验目的
1、熟悉JDBC常用API
2、掌握数据库联接、更新等操作

在这里插入图片描述
在这里插入图片描述

Java图形化界面设计代码:
JTextField jid = new JTextField(10);
JTextField jname = new JTextField(10);
JTextField jsex = new JTextField(10);
JTextField jshanchu = new JTextField(10);
JTextField j_id = new JTextField(10);
JTextField j_name = new JTextField(10);
JButton btn = new JButton(“确认添加”);
JButton btn1 = new JButton(“删除信息”);
JButton btn3 = new JButton(“删除一个人”);
JButton btn4 = new JButton(“查询数据库”);

初始化数据库的内容,连接JDBC
public class DataBase {
Connection conn=null;
Statement st=null;
public void Connect ()throws
SQLException,java.lang.ClassNotFoundException{
try {
Class.forName(“com.mysql.jdbc.Driver”);
String url=“jdbc:mysql://localhost:3306/test”;
String user=“root”;
String password=“123”;
conn=DriverManager.getConnection(url, user, password);
System.out.println(“链接数据库成功!”);
}catch (Exception e){
System.out.println(“链接数据库失败!”);
System.out.println(e.getMessage());
}
}

对数据实现信息添加:
public void addPerson(int id,String name,String sex) throws SQLException {
st=conn.createStatement();
st.executeUpdate(“insert into person” +
" values ("+id+",’"+name+"’,’"+sex+"’)");
System.out.println(“添加信息成功!”);
}

对数据实现信息删除:
public void delPerson(int id) throws SQLException {
st=conn.createStatement();
String sql1 = “delete from person “+” where id= '”+id+"’; ";
st.executeUpdate(sql1);
System.out.println(“删除信息成功”);
}

对数据实现信息查询
public void queryPerson(){
try{
st=conn.createStatement();
String StrSQL=“select * from person”;
ResultSet rs=st.executeQuery(StrSQL);
System.out.println(“person表的数据如下:”);
System.out.println("----------------!");
System.out.println("–编号"+" --姓名"+"–性别");
System.out.println("-------------------");
while (rs.next()){
String id = String.valueOf(rs.getInt(“id”));
String name = rs.getString(“name”);
String sex = rs.getString(“sex”);
System.out.println("–"+id+" --"+name+"–"+sex);
}
}catch (SQLException e){
System.out.println(“加载失败!”);
System.out.println(e.getMessage());
}
}

对数据库实现信息修改
public void xiugai(int id,String name){
try {
st=conn.createStatement();
String sql1 = “update person set name=? where id=?”;
PreparedStatement ps = conn.prepareStatement(sql1);
ps.setInt(2,id);
ps.setString(1,name);
ps.executeUpdate();
System.out.println(“修改成功”);
} catch (SQLException e) {
e.printStackTrace();
}
}
完整代码:
Github:

标签:06,String,04,System,2021,println,JTextField,id,out
来源: https://blog.csdn.net/qq_41785191/article/details/115463428