日期:2014-05-16 浏览次数:20521 次
jdbc 连接mysql数据库
?
package com.study.everyday.apr.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class Jdbc { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/bob"; // jdbc:mysql://[hostname][:port]/dbname // jdbc:mysql://localhost/addressbook?user=root&password=jjx String user = "root"; String password = ""; //数据库密码为空 String sql = "select classId,className from bob.class limit 0, 50 "; try { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } Connection con = DriverManager.getConnection(url, user, password); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { System.out.println(rs.getString("classId") + " " + rs.getString("className")); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
?
注意:
1.驱动下载地址:
http://dev.mysql.com/downloads/connector/j/5.1.html
?选择相应运行环境的点击 Download 下载,
还要登陆,第一次使用就选择 New Users 的 Proceed ,输入所要信息,即可下载。
?
附件里有我刚下载的驱动:
mysql-connector-java-5.1.7.zip
?
将驱动放到 Libraries 中。
?
?
用的数据库数据:
/*字段信息 - bob.class*/ ---------------------------- Field Type Collation Null Key Default Extra Privileges Comment --------- ----------- -------------- ------ ------ ------- -------------- ------------------------------- ------- classId int(11) (NULL) NO PRI (NULL) auto_increment select,insert,update,references className varchar(50) gbk_chinese_ci YES (NULL) select,insert,update,references /*索引信息 - bob.class*/ ---------------------------- Table Non_unique Key_name Seq_in_index Column_name Collation Cardinality Sub_part Packed Null Index_type Comment ------ ---------- -------- ------------ ----------- --------- ----------- -------- ------ ------ ---------- ------- class 0 PRIMARY 1 classId A 3 (NULL) (NULL) BTREE /*DDL 信息 - bob.class*/ -------------------------- Table Create Table ------ ------------------------------------------------- class CREATE TABLE `class` ( `classId` int(11) NOT NULL auto_increment, `className` varchar(50) default NULL, PRIMARY KEY (`classId`) ) ENGINE=InnoDB DEFAULT CHARSET=gbk CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC
?
?
?
?
?