1.創建數據庫
1 create database jdbc;

2.創建數據表
1 create table create table stu10( id int(10) primary key auto_increment, name varchar(20) not null, age varchar(10) not null, address varchar(20) not null);

3.通過insert語句增加數據
1 insert into stu10 values(1,'碼-奴','20','浙江嘉興');

4.創建連接數據庫類
1 package com.tu.jdbc;
2
3 import java.sql.Connection;
4 import java.sql.DriverManager;
5 import java.sql.SQLException;
6
7 public class Jdbc_con {
8 public Connection getConnection(){
9 try {
10 //加載數據庫驅動
11 Class.forName("com.mysql.jdbc.Driver");
12 //連接數據庫
13 return DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc","root","123");
14 } catch (Exception e) {
15 // TODO Auto-generated catch block
16 e.printStackTrace();
17 }
18 return null;
19 }
20
21 public void closeConection(Connection con){
22 if(con!=null){
23 try {
24 con.close();
25 } catch (SQLException e) {
26 // TODO Auto-generated catch block
27 e.printStackTrace();
28 }
29 }
30 }
31 }
5.創建測試類
1 package com.tu.jdbc;
2
3 import java.sql.Connection;
4 import java.sql.ResultSet;
5 import java.sql.SQLException;
6 import java.sql.Statement;
7
8 public class Test {
9
10 public static void main(String[] args) {
11 Test ts = new Test();
12 ts.list();
13
14 }
15
16 public void list() {
17 Jdbc_con jc = new Jdbc_con();
18 Connection jdbc = jc.getConnection();
19 String sql = "select id,name from stu10";
20 try {
21 Statement sm = jdbc.createStatement();
22 ResultSet rs = sm.executeQuery(sql);
23 while (rs.next()) {
24 int id = rs.getInt(1);
25 String name = rs.getString(2);
26 System.out.println(id + name);
27 }
28 } catch (SQLException e) {
29 // TODO Auto-generated catch block
30 e.printStackTrace();
31 }
32
33 }
34 }
