Java 应用程序 - 如何在 netbeans 中显示来自 mysql 数据库的所有记录?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18905941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java application - How to display all the records from mysql database in netbeans?
提问by Марко Лучи?
I`m having trouble with showing all the records from my database... I got database 'library' and table 'books'. Structure of 'members' : id, title, description, author, publisher, yearPublished.
我在显示数据库中的所有记录时遇到问题...我得到了数据库“library”和表“books”。“成员”的结构:id、标题、描述、作者、出版商、出版年份。
Here is my java code method:
这是我的java代码方法:
public static void preuzmi() throws ClassNotFoundException, InstantiationException, SQLException, IllegalAccessException{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/library", "root","");
Statement st = conn.createStatement();
st.executeQuery("select * from books");
ResultSet rs = st.getResultSet();
while(rs.next())
System.out.println(rs.getString("title"));
System.out.println(rs.getString("description"));
System.out.println(rs.getString("author"));
System.out.println(rs.getString("publisher"));
System.out.println(rs.getString("yearPublished"));
}
when i run this method preuzmi(); in main class it shows me only titles from db...
How can i show other records??? Please help me. THANKS IN ADVANCE!!!
当我运行这个方法 preuzmi(); 在主课中,它只显示来自 db 的标题......
我如何显示其他记录???请帮我。提前致谢!!!
采纳答案by Simon Forsberg
You are missing braces around your while-statement.
你的 while 语句周围缺少大括号。
while(rs.next()) { // this tiny little '{' is reeeaaaally important here
System.out.println(rs.getString("title"));
System.out.println(rs.getString("description"));
System.out.println(rs.getString("author"));
System.out.println(rs.getString("publisher"));
System.out.println(rs.getString("yearPublished"));
}
When you don't put braces after a while, if, for, etc. only the directly following statement will be executed. The rest will be executed after the entire loop is over.
一段时间后不加大括号时,if、for 等只会执行紧随其后的语句。其余的将在整个循环结束后执行。