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 stubClass.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檔案。