日期:2014-05-20 浏览次数:21128 次
public class Main {
public static void main(String[] args) {
//驱动程序名
String driver = "com.mysql.jdbc.Driver";
//URL指向要访问的数据库名字:
String url = "jdbc:mysql://localhost/Mysql_test";
//Mysql配置用户名:
String user = "root";
//Mysql配置密码:
String password = "LJZKID";
try {
//加载驱动程序
Class.forName(driver);
} catch (ClassNotFoundException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
try {
//连接数据库
Connection con = DriverManager.getConnection(url, user, password);
if(!con.isClosed())
System.out.println("Succeeded connecting to the Database!");
//statement用来执行SQL语言
Statement st = con.createStatement();
//要执行的SQL语言
String sql = "select * from tablename";
//结果集
ResultSet rs = (ResultSet)(Statement) st.executeQuery(sql);
while( rs.next() ) {
//选择col这列数据
String name = rs.getString("col1");
System.out.println("name=" +name );
}
rs.close();
con.close();
} catch (SQLException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}