简体   繁体   English

Java MySQL检查数据库中是否存在值

[英]Java MySQL check if value exists in database

I am trying to check, if a specific value already exists in my database. 我试图检查,如果我的数据库中已存在特定值。 I am accessing database from java standalone app using JDBC (queries for inserting records into db work so my setup and connection are ok). 我使用JDBC从java独立应用程序访问数据库(查询将记录插入数据库工作,所以我的设置和连接都可以)。

String queryCheck = "SELECT * from messages WHERE msgid = " + msgid;
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(queryCheck); // execute the query, and get a java resultset

// if this ID already exists, we quit
if(rs.absolute(1)) {
     conn.close();
     return;
}

I am getting this error (there is apparently something wrong with my SQL syntax): 我收到此错误(我的SQL语法显然有问题):

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'd-f05708071f8f' at line 1

However, if I try to execute this command in my MySQL command line, it works! 但是,如果我尝试在MySQL命令行中执行此命令,它可以工作! Can you tell me, whats wrong with my statement? 你能告诉我,我的陈述有什么不对吗? Thanks for any tips! 谢谢你的任何提示!

You need to wrap a String in quotes in MySQL, so the query needs to be 你需要在MySQL中用引号包装一个String ,所以查询需要

SELECT * from messages WHERE msgid = 'd-f05708071f8f';

Not

SELECT * from messages WHERE msgid = d-f05708071f8f;

So the code should read 所以代码应该读

String queryCheck = "SELECT * from messages WHERE msgid = '" + msgid + "'";

I would suggest using a PreparedStatement to avoid these sorts of issues and any risk of SQL injection: 我建议使用PreparedStatement来避免这些问题以及SQL注入的任何风险:

final String queryCheck = "SELECT * from messages WHERE msgid = ?";
final PreparedStatement ps = conn.prepareStatement(queryCheck);
ps.setString(1, msgid);
final ResultSet resultSet = ps.executeQuery();

Using string concatenation for query building is considered very bad practice. 使用字符串连接进行查询构建被认为是非常糟糕的做法。 Has been for a long time now. 已经很久了。

Further I would suggest using select count(*) rather than the full select * as this returns much less data (think of the size of the ResultSet ) and MySQL can optimise it too. 此外,我建议使用select count(*)而不是完整select *因为这会返回更少的数据(想想ResultSet的大小),MySQL也可以优化它。

final String queryCheck = "SELECT count(*) from messages WHERE msgid = ?";
final PreparedStatement ps = conn.prepareStatement(queryCheck);
ps.setString(1, msgid);
final ResultSet resultSet = ps.executeQuery();
if(resultSet.next()) {
    final int count = resultSet.getInt(1);
}

You need to use bind variables. 您需要使用绑定变量。

 PreparedStatement st = conn.prepareStatement(
    "SELECT * from messages WHERE msgid = ?");
 st.setString(1, msgid);
 ResultSet rs = st.executeQuery(queryCheck); 

Or get into manual quoting, but that is risky. 或者进入手动报价,但这是有风险的。

In addition to preventing SQL injection, prepared statements should also improve performance if you run the same query repeatedly. 除了防止SQL注入之外,如果重复运行相同的查询,预准备语句也应该提高性能。

Since msgid is a varchar you need to surround the value in the where clause with single quotes. 由于msgid是一个varchar,你需要用where引号括起where子句中的值。

String queryCheck = "SELECT * from messages WHERE msgid = '" + msgid + "'";

Dynamically generating SQL strings is not recommend however since it can expose your application to sql injection. 但是不建议动态生成SQL字符串,因为它可以将应用程序暴露给sql注入。

Instead use a PreparedStatement : 而是使用PreparedStatement

            String queryCheck = "SELECT * from messages WHERE msgid = ?";
            PreparedStatement st = conn.prepareStatement(queryCheck);
            st.setString(1, msgid);
            ResultSet rs = st.executeQuery();

Use single quotes arount the parameter: 使用单引号参数:

"SELECT * FROM messages WHERE msgid = '" + msgid + "'";

Or better you use prepared statements . 或者你更好地使用预备语句

You can try this: 你可以试试这个:

String queryCheck = "SELECT * from messages WHERE msgid = '" + msgid + "'";

You have missed quotes around msgid. 你错过了msgid的引用。 (I'm assuming that msgid is String and not Integer value. ) (我假设msgidString而不是Integer值。)

您需要使用单引号

SELECT * from messages WHERE msgid = 'd-f05708071f8f'; 
String sql1 ="SELECT Time FROM monday_wednesday WHERE Time ='"+time.getSelectedItem()+"'";
pst=con.prepareStatement(sql1);
rs=pst.executeQuery();
if(rs.next()) {
    if(rs.getString("Time").equals(time.getSelectedItem())) {
        JOptionPane.showMessageDialog(null,"Time is already taken","",JOptionPane.INFORMATION_MESSAGE); 
    }
} else {
    String sql="INSERT INTO monday_wednesday(pfname,pmname,plname,Birthdate,Gender,Address,City,Contact,Contactperson,Time,Date)\n" + "VALUES ('"+txtFirstName1.getText()+"','"+txtMiddleName1.getText()+"','"+txtLastName1.getText()+"','"+d+"','"+gender.getSelectedItem()+"','"+ txtAddress.getText()+"','"+txtCity.getText()+"','"+txtContact.getText()+"','"+txtContactPerson1.getText()+"','"+time.getSelectedItem()+"','"+dateFormat.format(date)+"')";
}

Just a simple duplicate entry algorithm 只是一个简单的重复输入算法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM