我使用JDBC建立了与数据库的连接,但是,我想创建一个这样的查询:SELECT idCows FROM cows其中Name =" someVariable"。
在这种情况下," someVariable"是一个String,我将从我的HTML中的表单中获取,所以问题是如何检索该变量并将其设置为查询,以便每次搜索名称时它都会给我正确的答案。
我的代码如下所示:
import java.sql.*;
public class Connector {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.mysql-connector-java-5.1.12-bin");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String url = "jdbc:mysql://localhost/Farm";
try {
Connection con = DriverManager.getConnection(url, "admin", "admin123");
Statement stat = con.createStatement();
ResultSet rs = stat.executeQuery("SELECT idCows FROM cows WHERE Name = "+name);
while(rs.next()) {
String n = rs.getString("Name");
System.out.println(n);
}
stat.close();
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
答案 0 :(得分:0)
您必须将变量放在单引号中,例如
ResultSet rs = stat.executeQuery("SELECT idCows FROM cows WHERE Name = '"+name+"'");
或者,更好的是,使用PreparedStatement。
PreparedStatement stat = con.prepareStatement("SELECT idCows FROM cows WHERE Name = ?");
stat.setString(1, name);
ResultSet rs = stat.executeQuery();
然后做
String n = rs.getString("idCows");
而不是"Name
"