ResultSet的java Can getString()方法可用于从MySQL表获取文本类型列的值?
我试图从MySQL数据库中的表中检索文本字段的值。 MySQL版本是5.6.21 &;我使用的是mysql-connector-java-5.1.18-bin。罐子
我的档案如下
import java.sql.*;
public class DatabaseConnection {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/book";
// database credentials
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Creating statement...");
stmt = conn.createStatement();
String query;
query = "Select b_name, description columns from brands";
ResultSet rs = stmt.executeQuery(query);
while(rs.next()) {
String first_name = rs.getString("b_name");
String description = rs.getString("description");
System.out.println(first_name);
System.out.println(description);
}
rs.close();
stmt.close();
conn.close();
} catch(SQLException se) {
se.printStackTrace();
} catch(ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
} catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
} catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}
}
这意味着我的列不存在,尽管我在另一个表上尝试过,但它在VARCHAR列上有效,但在文本列上无效
此错误显示为:
但是该表有一个名为description的列:
# 1 楼答案
问题不在于列类型是文本。 可以使用
getString
获取文本类型的值。 您可以在documentation中进行验证问题出在查询中:
“专栏”有个错误。 以这种方式编写,
description
列实际上在结果集中重命名为columns
。 如果你做了rs.getString("columns")
,你会得到这个值。 但那不是你想做的。要通过删除该单词来修复查询: