import java.sql.*;public class Jdbc{
public static void main(String[] args){
Connection conn =null;
Statement stat =null;
ResultSet rs = null;
try {
new com.mysql.jdbc.Driver();
conn = DriverManager.getConnection(
"jdbc:mysql://localhost/test?user=root&password=root&useUnicode=true&characterEncoding=GBK" );
stat = conn.createStatement();
rs = stat.executeQuery("select * from test");
while(rs.next()){
System.out.print(rs.getString("id") + ":");
System.out.println(rs.getString("name"));
}
} catch (SQLException ex) {
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}
try {
if(rs!=null){
rs.close();
rs= null;
}
if(stat!=null){
stat.close();
stat=null;
}
if(conn!=null){
conn.close();
conn =null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
这段程序中new com.mysql.jdbc.Driver();是什么意思?好像不是标准的Java语法。
但它只有等号的右半部分,这是为什么呢?
你new com.mysql.jdbc.Driver();这一句,确实不明白你new 的对象,到底是谁在引用
Jdbc.java:10: 软件包 com.mysql 不存在
Class.forName(com.mysql.jdbc.Driver).newInstance();
^
1 错误
注意 自己的数据库版本和JAR要对应
A a = (A)Class.forName("package.A").newInstance();
和
A a = new A();
是一样的。
简而言之:
Class.forName(xx.xx.xx)返回的是一个类
Class.forName(xx.xx.xx)要求JVM查找并加载指定的类——也就是说JVM会执行指定类的静态代码块。
com.mysql.jdbc.Driver也只不过是个类而已 new com.mysql.jdbc.Driver()也没什么不可以的;当一个类开始被执行的时候,众所周知首先要先加载静态块,所以,如此实例化也没什么大不了的,只不过不符合某些所谓的规范而已。