浏览 1874 次
锁定老帖子 主题:java 连接 MySQL数据库
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2008-09-04
用工具时间太长啦我害怕吧一些东西都给忘啦!! 呵呵!!!! package net.conn; import java.sql.*; public class MySqlDemo { /** * @param args * @throws SQLException */ public static void main(String[] args) throws SQLException { // TODO Auto-generated method stub String dbName = "root"; String dbPwd = "admin"; String sql = "jdbc:mysql://localhost/hibernate?useUnicode=true&characterEncoding=GBK"; Connection con; Statement stmt; ResultSet rs; //定位驱动 try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } // 建立连接 con = DriverManager.getConnection(sql, dbName, dbPwd); stmt = con.createStatement(); rs = stmt.executeQuery("select * from mocake"); ResultSetMetaData meta_data = rs.getMetaData(); for (int i_col = 1; i_col <= meta_data.getColumnCount(); i_col++) { System.out.print(meta_data.getColumnLabel(i_col) + " "); } System.out.println(); while (rs.next()) { for (int i_col = 1; i_col <= meta_data.getColumnCount(); i_col++) { System.out.print(rs.getString(i_col) + " "); } System.out.println(); } //关闭流 rs.close(); stmt.close(); con.close(); } } 在数据库中必须要有相应的表: mocake.sql create table mocake( id int primary key, name varchar(20)not null, pwd varchar(20)not null ) insert into mocake values (1,'niceo_1','12'); insert into mocake values (2,'niceo_2','123'); insert into mocake values (3,'niceo_3','13'); insert into mocake values (4,'niceo_4','23'); 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |