我有一个用 java 编写的程序。此程序在从 dos 提示符下运行时引发未找到驱动程序类
import java.sql.*;
public class SimpleDb {
public static void main(String[] args)throws SQLException,ClassNotFoundException
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.get connection("jdbc:mysql://host/db");
Statement sta = con.create statement();
ResultSet rs = sta.executeQuery(query);
con.close();
}
}
请帮忙
最佳答案
您需要将 MySQL 连接器添加到您的项目中:http://dev.mysql.com/downloads/connector/j/
此外,不再需要 Class.forName
,您应该使用 try-with-resources 进行适当的异常处理和资源管理:
try (Connection conn = DriverManager.getConnection("...") {
PreparedStatement ps = conn.prepareStatement("...");
try (ResultSet rs = ps.executeQuery()) {
/* Parse result */
}
} catch (SQLException ex) {
for (Throwable t : ex) {
t.printStackTrace();
}
}
关于java - 在java中从JDBC连接到MySql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30576502/