Class.forName().newInstance()在JDBC中的作用
package InputSql;
import java.sql.*;
public class Sql {
private static String urlName = null;
private static String DriverName = "com.mysql.jdbc.Driver";
private static String user = "root";
private static String pwd = "18157143347";
private static Connection c = null;
/*
* connect方法用来将根据参数-databaseName,与指定的数据库连接
* DriverManager类中的getConnexttion()静态方法即可返回一个与指定的数据库相连的Connection对象
*/
public static void connect(String databaseName) {
urlName = "jdbc:mysql://localhost/" + databaseName;
try {
c = DriverManager.getConnection(urlName, user, pwd);
} catch (Exception ex) {
ex.printStackTrace();
}
}
/*
* 在利用connection.prepareStatement()方法产生Statement对象,调用Statement的excuteQuery()方法即可
* 向connection对象连接的数据发送搜索sql语句了,并返回储存查询值的resultSet对象
* 利用resultSet对象中的getMetaData
* ()得到记录ResultSet的列信息的MetaData对象,即列的属性和列数,即可打印出整个表的信息
*/
public static void search(String sql) {
ResultSet search = null;
try {
PreparedStatement ps = c.prepareStatement(sql);
search = ps.executeQuery(sql);
search.last();
int cols = search.getMetaData().getColumnCount();
search.beforeFirst();
while (search.next()) {
for (int i = 1; i <= cols; i++) {
System.out.print(search.getString(i) + " ");
}
System.out.println();
}
} catch (
SQLException e) {
e.printStackTrace();
} finally {
try {
search.close();
c.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/*
* 主方法
*/
public static void main(String[] args) {
try {
// 这里Class.forName(DriverName)去掉程序也可正常进行,在这里没什么作用
Class.forName(DriverName).newInstance(); } catch (
ClassNotFoundException e) {
e.printStackTrace();
} catch (
IllegalAccessException ex) {
ex.printStackTrace();
} catch (
InstantiationException ex) {
ex.printStackTrace();
}
connect("jisuanji122");
search("select * from student");
}
}
红色字体部分代码的作用实在不知,即使注释掉了程序运行也正常
------解