简体   繁体   English

从jdbc中检索数据

[英]Retrieving data from jdbc

I have a string array which holds the name of 500 stocks. 我有一个字符串数组,其中包含500个股票的名称。 Now i have a table in my mysql database which holds the symbol for more than 1000 stocks alonwith their name. 现在我在我的mysql数据库中有一个表,其中包含超过1000个股票的符号。 What i would like to do is retrieve the symbol of those 500 stocks from the table i have. 我想做的是从我的表中检索那500个股票的符号。 I have tried the following code 我试过以下代码

Class.forName("com.mysql.jdbc.Driver");
Connection conn=DriverManager.getConnection("jdbc:mysql//localhost/mydatabase","user","pass");
PreparedStatement stmt = conn.prepareStatement("SELECT (NAME) FROM stocks1 WHERE FULLNAME =?"); 
for(int i1=0;i1<i;i1++)
{   
  stmt.setString(1, name[i1]); 


  stmt.addBatch(); 
} 
ResultSet t=stmt.executeQuery(); 
while(t.next())
  System.out.println(t.getString("NAME"));

But it doesnt work. 但它不起作用。 Nothing is printed. 什么都没打印。 I think i am making a mistake in stmt.addBatch(). 我想我在stmt.addBatch()中犯了一个错误。 Also if i wanted the name[i1] to be follwed by a wildcard charcter(%) how would i do this. 此外,如果我希望名称[i1]被通配符字符(%)所示,我将如何做到这一点。

You could create a table for the stocks in your string array and do a join with your stocks1 table. 您可以为字符串数组中的股票创建一个表,并与stocks1表进行连接。

Let's say the table for your arraystocks is named stocksperuser with one column FULLNAME the code looks like this: 假设您的阵列表的表名为stocksperuser,其中一列为FULLNAME,代码如下所示:

Class.forName("com.mysql.jdbc.Driver");
Connection conn=DriverManager.getConnection("jdbc:mysql//localhost/mydatabase","user","pass");
PreparedStatement stmt = conn.prepareStatement("SELECT NAME FROM stocks1 WHERE FULLNAME is in (SELECT FULLNAME FROM arraystocks)"); 
ResultSet t=stmt.executeQuery(); 
while(t.next()) {
    System.out.println(t.getString("NAME"));
}

For including wildcard, you can do as shown below. 要包含通配符,您可以执行如下所示的操作。

In your select statement remove = and add LIKE 在你的select语句中删除=并添加LIKE

PreparedStatement stmt = conn.prepareStatement("SELECT (NAME) FROM stocks1 WHERE FULLNAME LIKE ?");   

add % in the setString method. 在setString方法中添加%。

ps.setString(1, name[i1]+ "%");

Also , for empty rows issue , please check if both the comparison column's case are the same,either they should be in upper or in lower. 另外,对于空行问题,请检查比较列的情况是否相同,它们应该在上面还是下面。 If its not , then you can convert while comparing as shown below. 如果不是,那么您可以在比较时进行转换,如下所示。

SELECT (NAME) FROM stocks1 WHERE upper(FULLNAME) LIKE ?   

ps.setString(1, upper(name[i1])+ "%");

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

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