Eclipse 連接MySql數據庫總結
一、在MySql中創建數據庫,並創建表,向表中插入數據
1、創建數據庫
create database select_test
2、創建表
create table teacher_table( Id int, Name Varchar(20), Sex Varchar(2) )
3、向表中插入數據(這里插入三條測試數據)
insert into teacher_table values(1,'zhangsan','ma'); insert into teacher_table values(2,'lisi','fe'); insert into teacher_table values(3,'wangwu','ma');
二、配置Eclipse。
配置之前請先下載mysql-connector-java-5.1.15-bin.jar文件。
右鍵單擊包所在的工程包(project),Build Path ---> Configure Build Path,在彈出的窗口中選擇 Add External JARs。把你下載並解壓出來的mysql-connector-java-5.1.15-bin.jar選中。如圖
三、編寫連接代碼。
數據庫名:select_test
用戶名:root
密碼:123456
連接成功后顯示teacher_table表中的數據。
import java.sql.*; class ConnMySql { /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { // TODO Auto-generated method stub Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection( "jdbc:mysql://127.0.0.1:3306/select_test", "root","123456"); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("select * from teacher_table"); while (rs.next()) { System.out.println(rs.getInt(1) + "\t" +rs.getString(2) + "\t" +rs.getString(3) ); } if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); } } }
總結:Elipse連接MySql數據庫要求下載mysql-connector-java-5.1.15-bin.jar文件。