我已经编写了一个程序,它在mysql数据库中搜索给定的印地语单词,并检索存储在数据库中的相应英文名称。当我在select语句中直接给出印地语单词时,它工作得很好,但是我想使用一个变量来给出它,这样它可以更通用,但是我没有得到同样的结果..有谁能帮我解决这个问题..谢谢
这是我写的代码
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
import com.microsoft.sqlserver.jdbc.*;
import java.sql.*;
public class Example {
public static void main(String[] argv) {
try {
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e)
{
System.out.println("Where is your MySQL JDBC Driver?");
e.printStackTrace();
return;
}
Connection connection = null;
SQLServerDataSource dataSource = new SQLServerDataSource();
dataSource.setServerName("COMP-PC");
dataSource.setPortNumber(1433);
dataSource.setDatabaseName("concept");
dataSource.setUser("root");
dataSource.setPassword("abc");
try
{
connection = dataSource.getConnection();
connection.setAutoCommit(false);
System.out.println("Connected to server !!!");
Statement select = connection.createStatement();
String var="N'हल्दी'";
ResultSet result = select.executeQuery
("SELECT Name, Id FROM MConcept where CName=N'हल्दी'");
**// When given like the above statement it works fine
("SELECT Name, Id FROM MConcept where CName='"+var+" ' ");
**//This does not give result
System.out.println("Got results:");
while(result.next()) { // process results one row at a time
String Name = result.getString(1);
int ID = result.getInt(2);
System.out.println("name = " + Name);
System.out.println("id = " + ID);
}
select.close();
connection.close();
}
catch (SQLException e)
{
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
if (connection != null)
{
System.out.println("Successfully connected!");
}
else
{
System.out.println("Failed to make connection!");
}
}
}
最佳答案
你的第二句话不正确。
应该是
"SELECT Name, Id FROM MConcept where CName=" + var
但我强烈建议使用PreparedStatement并阅读这个SQL注入的警告故事->http://xkcd.com/327/