MainClass .java
public class MainClass
{
public String StrUrl="jdbc:mysql://localhost/vivek";
public String StrUid;
public String StrPwd= "";
public static String StrUser;
public MainClass() {
this.StrUid = "root";
}
}
Addproducts.java
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String proid="";
proid=productid.getText();
String proname="";
proname=productname.getText();
String purcst="";
purcst=purchasecost.getText();
if (proid.isEmpty()==true)
{
JOptionPane.showMessageDialog(null,"Enter User Name");
return;
}
if (proname.isEmpty()==true)
{
JOptionPane.showMessageDialog(null,"Enter Password");
return;
}
try
{
//get database connection details
MainClass mc=new MainClass();
//open connection
Connection connection;
connection=DriverManager.getConnection(mc.StrUrl,mc.StrUid,mc.StrPwd);
String str="";
str="INSERT INTO login('uname', 'password') VALUES (?, ?)";
PreparedStatement pst=connection.prepareStatement(str);
pst.setString(1, proid);
pst.setString(2, proname);
ResultSet rs;
rs=pst.executeQuery();
}
catch(Exception e){
System.err.println(e);
System.exit(1);
}
}
java.sql.SQLException: Can not issue data manipulation statements with executeQuery().
Java Result: 1
i tried
rs=pst.executeUpdate();
error: incompatible types: int cannot be converted to ResultSet
rs=pst.executeUpdate();
答案 0 :(得分:1)
您需要使用executeUpdate
而不是executeQuery
,但这会返回受此更改影响的行数,例如
try (Connection connection=DriverManager.getConnection(mc.StrUrl,mc.StrUid,mc.StrPwd)) {
String str="";
str="INSERT INTO login('uname', 'password') VALUES (?, ?)";
try (PreparedStatement pst=connection.prepareStatement(str)) {
pst.setString(1, proid);
pst.setString(2, proname);
int count=pst.executeQuery();
System.out.println(count + " rows changed");
}
} catch (SQLException exp) {
exp.printStackTrace();
}
如果您想从数据库中检索值,则需要使用select
语句,例如......
try (Connection connection=DriverManager.getConnection(mc.StrUrl,mc.StrUid,mc.StrPwd)) {
String str="";
str="select * from login where name = ? and password = ?";
try (PreparedStatement pst=connection.prepareStatement(str)) {
pst.setString(1, proid);
pst.setString(2, proname);
try (ResultSet rs = pst.executeQuery()) {
while (rs.next() {
//... Process each result...
}
}
}
} catch (SQLException exp) {
exp.printStackTrace();
}
仔细查看JDBC(TM) Database Access了解更多详情......