我尝试了一个基本程序来将数据库表中的数据检索到Java程序中。在编译结束时,运行代码时会发生异常。控制台中未显示任何错误。它显示异常消息
import java.sql.*;
public class class1 {
public static void main(String args[]){
String url = "jdbc:mysql://localhost:3306//orders";
String username = "root";
String password = "Luxan@22";
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, username, password);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT CUST_NAME FROM CUSTOMERS");
System.out.println("List of Registered customers: ");
while(rs.next()){
System.out.println(rs.getString("cust_name"));
}
st.close();
con.close();
}
catch(Exception e){
System.out.println("An Exception error occured while processing JDBC programme");
}
}
}
下面是我的控制台窗口中的输出
Fri Jan 17 19:34:24 IST 2020 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
An Exception error occured while processing JDBC programme
public class Class1 {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver"); // this line is optional since Java 1.6 Normally for MySQL you shouldn't have to do this
// This is called "try-with-resources". It means that inside your "try" declaration you
// tell Java what things you want to open (here you wnat to open a connection)
// and it will automatically close any connection (on failure or success) for you
try (
Connection connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/orders", // before the database name there is only one /
"root", // the database user
"password"); // the password
Statement statement = connection.createStatement() // the same try-with resources can open the statement for your
) {
ResultSet rs = statement.executeQuery("SELECT CUST_NAME FROM CUSTOMERS");
while (rs.next()) {
System.out.println(rs.getString("cust_name"));
}
} catch (SQLException ex) {
Logger.getLogger(Class1.class).log(Level.SEVERE, null, ex); // this will properly log your SQLException. Don't be afraid, SQL error messages are scary and Java Exceptions are impressive. But they will tell you where the problem is
}
} catch (ClassNotFoundException ex) { // if you register your driver you need to catch the exception as well
Logger.getLogger(Class1.class).log(Level.SEVERE, null, ex);
}
}
}
您可以在MkYong上阅读有关此示例的更多信息。
希望对您有帮助。另外一件事:
类名以大写字母开头:
Class1
,而不是class1
。因为变量名以小写字母开头。假设您要创建一个名为car
的类的实例。然后,您会说car car = new car();
这是不可读的。Car car = new Car()
很清楚:)