与数据库的Java连接不起作用

时间:2013-04-24 23:42:32

标签: java connection database-connection

我需要有关此代码的帮助才能建立与数据库的连接。

try
{
String str="SELECT * FROM Author WHERE city LIKE 'P%'";
 Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con =
DriverManager.getConnection     
("jdbc:odbc:myds;databaseName=Library;user=sa;password=password123");
Statement  =con.createStatement();
ResultSet rs= executeQuery();
System.out.println("Author ID\tAuthor Name\tCity");
while (rs.next())
{
String id=rs.getString("au_id");
String name=rs.getString("au_name");
String city=rs.getString("city");
System.out.print(id+"\t");
if (name.length() <=7)
System.out.print(name+"\t\t");
else
System.out.print("\t"+name+"\t");
System.out.println(city);
}
}
catch(Exception ex)
{
System.out.println("Error occurred");
System.out.println("Error:"+ex); 

上述代码有什么问题?

1 个答案:

答案 0 :(得分:1)

我认为它会是那样的

String str="SELECT * FROM Author WHERE city LIKE 'P%'";
// Some stuff 
Statement stmt = con.createStatement(); //stmt added
// Some more stuff 
ResultSet rs = stmt.executeQuery(str); // stmt and str added

你应该看看Execute SQL Queries with Java Application.