java 之連接mysql數據庫

1:新建類:
完成對數據庫的連接,並通過返回Connection。
在此之前要記得導入對MySQL數據庫的驅動(jar包)。網上一搜很多。


import java.sql.DriverManager;
import java.sql.SQLException;

import com.mysql.jdbc.Connection;

public class MyConnection {
    private static Connection connection;
    public MyConnection() {
        // TODO Auto-generated constructor stub
    }
    public static Connection getConnection(){
        String urlString = "jdbc:mysql://localhost:3306/shcoolapp?user=root&password=ffffff&useUnicode=true&characterEncoding=gbk";
        //String usernameString = "root";
        //String pd = "maths_112357";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = (Connection) DriverManager.getConnection(urlString);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return connection;
    }
    public static void closeCon() {
            try {
                if (connection!=null) {
                    connection.close();
                }
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }

2:新建操作類:
其中獲得上一個連接類中的Connection

public class UserDao {

    private Connection connection;
    public UserDao() {
        // TODO Auto-generated constructor stub

    }
    public UserDao(Connection connection) {
        super();
        this.connection = connection;
    }

    //以上就是最主要的過程,接下來你就可以操作你的數據庫了。
    //下面是我自己的一個例子,其中Students是我自己根據數據庫表創建的實體類

    public List<Students> getUserList(){
        userList = new ArrayList<Students>();
        String string = "SELECT * FROM web_test";
        ResultSet resultSet = null;
        Statement statement = null;
        try {
            statement = connection.createStatement();
            resultSet = statement.executeQuery(string);
            while (resultSet.next()) {
                Students stu = new Students();
                stu.setIdString(resultSet.getString("id"));
                stu.setAge(resultSet.getString("age"));
                stu.setNameString(resultSet.getString("name"));
                stu.setSex(resultSet.getString("sex"));
                stu.setXuehaStringo(resultSet.getString("xuehao"));
                userList.add(stu);
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            try {
                resultSet.close();
                statement.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return userList;
    }
發佈了61 篇原創文章 · 獲贊 21 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章