首页 新闻 搜索 专区 学院

Java实现对数据库的增删改查,网上找的代码,不知道是哪里写错了,求解答

1
悬赏园豆:20 [已解决问题] 解决于 2016-11-25 11:21

package ang;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import java.util.Vector;
import java.awt.*;
import javax.swing.*;

public class data extends JFrame implements ActionListener {
JButton add, select, del, update;
JTable table;
Object body[][] = new Object[50][5];
String fields[] = { "编号", "姓名", "性别", "年龄", "地址" };
Connection conn;
Statement st;
ResultSet rs;
JTabbedPane tp;
private String s;

public data() {
super("数据库操作");
this.setSize(400, 300);
this.setLocation(400, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel ps = new JPanel();

add = new JButton("添加");
select = new JButton("查询");
update = new JButton("更新");
del = new JButton("删除");

add.addActionListener(this);
select.addActionListener(this);
update.addActionListener(this);
del.addActionListener(this);

ps.add(add);
ps.add(select);
ps.add(update);
ps.add(del);

this.connection();
table = new JTable(body, fields);
tp = new JTabbedPane();
tp.add("S表", new JScrollPane(table));
this.getContentPane().add(tp, "Center");
this.getContentPane().add(ps, "South");

this.setVisible(true);


}

public void connection() {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;DatabaseName = studb","sa","svse");
st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.TYPE_FORWARD_ONLY);
} catch (Exception ex) {
// TODO: handle exception
System.out.println("连接错误");
}
}

public static void main(String[] args) {
// TODO Auto-generated method stub
data date = new data();
}

@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if (e.getSource() == add) {
add();
}
if (e.getSource() == select) {
select();
}
if (e.getSource() == update) {
update();
}
if (e.getSource() == del) {
del();
}
}

private void del() {
// TODO Auto-generated method stub
try {
int row = table.getSelectedRow();
String str = "delete s where SNO = '" + body[row][0] + "'";
st.executeUpdate(str);
JOptionPane.showMessageDialog(null, "数据已成功删除");
this.select();
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "删除数据错误!");
}
}

private void update() {
// TODO Auto-generated method stub
try {
int row = table.getSelectedRow();
JTextField t[] = new JTextField[8];
t[0] = new JTextField("输入姓名:");
t[0].setEditable(false);
t[1] = new JTextField();
t[1].setText((String) body[row][1]);
t[2] = new JTextField("输入性别:");
t[2].setEditable(false);
t[3] = new JTextField();
t[3].setText((String) body[row][2]);
t[4] = new JTextField("输入年龄:");
t[4].setEditable(false);
t[5] = new JTextField();
t[5].setText((String) body[row][3]);
t[6] = new JTextField("输入专业:");
t[6].setEditable(false);
t[7] = new JTextField();
t[7].setText((String) body[row][4]);
String but[] = { "确定", "取消" };
int go = JOptionPane.showOptionDialog(null, t, "修改信息", JOptionPane.YES_OPTION,
JOptionPane.INFORMATION_MESSAGE, null, but, but[0]);
if (go == 0) {
String nName = (String) t[1].getText();
String nsex = (String) t[3].getText();
int nage = Integer.parseInt(t[5].getText());
String ndept = (String) t[7].getText();
String str = "update s set sname = '" + nName + "',sex='" + nsex + "',age='" + nage + "',dept='" + ndept
+ "'where sno='" + body[row][0] + "' ";
st.executeUpdate(str);
JOptionPane.showMessageDialog(null, "修改数据成功!");
this.select();
st.executeUpdate(str);
JOptionPane.showMessageDialog(null, "数据已经成功插入!");
}

} catch (Exception ex) {
// TODO: handle exception
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "更新数据失败!");
}
}

private void select() {
// TODO Auto-generated method stub
String str = "select * from S";
filltable(str);
}

private void filltable(String str) {
// TODO Auto-generated method stub
try {
for(int x=0;x<body.length;x++){
body[x][0]=null;
body[x][1]=null;
body[x][2]=null;
body[x][3]=null;
body[x][4]=null;
}
int i = 0;
rs = st.executeQuery(s);
while(rs.next()){
body[i][0]=rs.getString("SNO");
body[i][1]=rs.getString("SNAME");
body[i][2]=rs.getString("SEX");
body[i][3]=rs.getString("AEG");
body[i][4]=rs.getString("DEPT");
i=i+1;
}
this.repaint(i);
} catch (Exception ex) {
// TODO: handle exception
ex.printStackTrace();
}
}
private void add() {
// TODO Auto-generated method stub
try {
JTextField t[] = new JTextField[10];
t[0] = new JTextField("输入学号:");
t[0].setEditable(false);
t[1] = new JTextField();
t[2] = new JTextField("输入姓名:");
t[2].setEditable(false);
t[3] = new JTextField();
t[4] = new JTextField("输入性别:");
t[4].setEditable(false);
t[5] = new JTextField();
t[6] = new JTextField("输入年龄:");
t[6].setEditable(false);
t[7] = new JTextField();
t[8] = new JTextField("输入专业:");
t[8].setEditable(false);
t[9] = new JTextField();
String but[] = {"确定","取消"};
int go = JOptionPane.showOptionDialog(null, t, "插入信息", JOptionPane.YES_OPTION, JOptionPane.INFORMATION_MESSAGE, null, but, but[0]);
if(go == 0){
try {
String nsno = (String)t[1].getText();
String nName = (String)t[3].getText();
int nsex = Integer.parseInt(t[5].getText());
int nage = Integer.parseInt(t[7].getText());
String ndept = (String)t[9].getText();
String str = "insert into s values('"+nsno+"','"+nName+"','"+nsex+"','"+nage+"','"+ndept+"',)";
st.executeUpdate(str);
JOptionPane.showMessageDialog(null, "数据已经成功插入!");
} catch (Exception ex) {
// TODO: handle exception
JOptionPane.showMessageDialog(null, "数据插入失败!");
}
}

} catch (Exception ex) {
// TODO: handle exception

}
}

}

 

 

 

 

运行后程序显示出窗体,但eclipse显示连接错误。

哇哈爽的主页 哇哈爽 | 初学一级 | 园豆:193
提问于:2016-11-25 10:03
< >
分享
最佳答案
0

你可以把方法 connection()中的catch()语句改改,改成下面这样,可以看到堆栈信息,贴出来给我看看。

public void connection() {
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;DatabaseName = studb","sa","svse");
            st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.TYPE_FORWARD_ONLY);
        } catch (Exception ex) {
            ex.printStackTrace();
            System.out.println("连接错误:" + ex.getMessage());
        }
    }

 

收获园豆:18
吸氧羊与肥汰狼 | 菜鸟二级 |园豆:280 | 2016-11-25 10:51

运行程序没报错也没异常,就是点击查询的时候报错。

哇哈爽 | 园豆:193 (初学一级) | 2016-11-25 10:59

@哇哈爽:图片太不清晰了,你把下面的堆栈信息以代码的形式贴出来给我看吧,我要看完整的堆栈信息才好定位问题,上面图片说你的代码里有参数为空,但是看不出来是哪個参数。

吸氧羊与肥汰狼 | 园豆:280 (菜鸟二级) | 2016-11-25 11:02

@吸氧羊与肥汰狼: 

java.lang.NullPointerException
at com.microsoft.sqlserver.jdbc.SQLServerStatement.ensureSQLSyntax(SQLServerStatement.java:702)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.doExecuteStatement(SQLServerStatement.java:728)
at com.microsoft.sqlserver.jdbc.SQLServerStatement$StmtExecCmd.doExecute(SQLServerStatement.java:689)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:5696)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1715)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:180)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:155)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeQuery(SQLServerStatement.java:616)
at ang.data.filltable(data.java:165)
at ang.data.select(data.java:151)
at ang.data.actionPerformed(data.java:80)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

哇哈爽 | 园豆:193 (初学一级) | 2016-11-25 11:04

@哇哈爽:你的 filltable() 方法,传进去的参数名称是 str,后面调用 executeQuery() 时的参数是 s,两个名称没匹配上吧?

吸氧羊与肥汰狼 | 园豆:280 (菜鸟二级) | 2016-11-25 11:11

@吸氧羊与肥汰狼: 

好流弊,确实解决了,厉害了,java哥

哇哈爽 | 园豆:193 (初学一级) | 2016-11-25 11:20

@吸氧羊与肥汰狼: 不过查询、删除、修改都可以用,就是添加不行,添加失败!

哇哈爽 | 园豆:193 (初学一级) | 2016-11-25 11:26

@哇哈爽: 你的 add() 方法里,下面这句话

String str = "insert into s values('"+nsno+"','"+nName+"','"+nsex+"','"+nage+"','"+ndept+"',)";

是不是应该改成

String str = "insert into s values('"+nsno+"','"+nName+"','"+nsex+"','"+nage+"','"+ndept+"')";

最后壹個逗号不需要

吸氧羊与肥汰狼 | 园豆:280 (菜鸟二级) | 2016-11-25 11:33

@吸氧羊与肥汰狼: 厉害,忽略细节了,来加个好友了,qq,微信啥的

哇哈爽 | 园豆:193 (初学一级) | 2016-11-25 11:36
其他回答(1)
0

连接错误?  是数据库没连上么?    看看你的数据库名,用户名和密码对不对

收获园豆:2
谁说不可以重名 | 园豆:15 (初学一级) | 2016-11-25 10:09

觉得不是,因为连接数据库的语句在其他程序里可以运行成功。网上说是哪个值是空的,具体也不清楚

支持(0) 反对(0) 哇哈爽 | 园豆:193 (初学一级) | 2016-11-25 10:15

@哇哈爽: 把报出的错误贴出来看一下

支持(0) 反对(0) 谁说不可以重名 | 园豆:15 (初学一级) | 2016-11-25 10:16

@谁说不可以重名: 貌似于这个上传图片还要开通博客啥的,好麻烦。其实程序运行并没有报错,eclipse里下面显示的就是   “连接错误”。应该是

public void connection() {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;DatabaseName = studb","sa","svse");
st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.TYPE_FORWARD_ONLY);
} catch (Exception ex) {
// TODO: handle exception
System.out.println("连接错误");
}
}

 

这里直接跳出来了,但是连接语句是有试过的,没问题,在想是不是哪的语句加载时数据库里的数据调不过来。

支持(0) 反对(0) 哇哈爽 | 园豆:193 (初学一级) | 2016-11-25 10:24

@哇哈爽: 把ex dump出来,你输出个连接错误有什么用。

支持(0) 反对(0) Daniel Cai | 园豆:10374 (专家六级) | 2016-11-25 10:26

@Daniel Cai: 

com.microsoft.sqlserver.jdbc.SQLServerException: 不支持并发。
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:190)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.<init>(SQLServerStatement.java:464)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.createStatement(SQLServerConnection.java:2157)
at ang.data.connection(data.java:59)
at ang.data.<init>(data.java:43)
at ang.data.main(data.java:69)

支持(0) 反对(0) 哇哈爽 | 园豆:193 (初学一级) | 2016-11-25 10:29

@Daniel Cai: 

网上找到的方案,把

st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.TYPE_FORWARD_ONLY);

改成

st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);

 

就没显示连接错误了,但是貌似于其他的功能还是用不了。

支持(0) 反对(0) 哇哈爽 | 园豆:193 (初学一级) | 2016-11-25 10:38
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册