Intellij IDEA通過java操作mysql數據庫

一、在項目中導入驅動包

**1、在mysql數據庫默認安裝位置(我的是C:\Program Files (x86)\MySQL\Connector J 8.0)複製
mysql-connector-java-8.0.11.jar;將其放到項目目錄下,
2、在IDEA:file->Project Structure->Moudles->dependencies中添加選項卡中選擇jars;

二、通過JDBC操作mysql數據庫

實現代碼如下:

import java.sql.*;

public class java_jdbc {
    private  static final String url="jdbc:mysql://localhost:3306/db_infomanager?useSSL=false&characterEncoding=utf-8&serverTimezone=Hongkong";
    private static final String UserNmae="root";
    private static final String pwd="0000";

    public static void update(){
        Connection connection=null;
        Statement stmt=null;

        ResultSet rst=null;
        try {
            //a.import the driver package and load the specific driver Class
            Class.forName("com.mysql.cj.jdbc.Driver");   //load the specific driver class;
            //b.Establish a connection to the database;
            connection = DriverManager.getConnection(url,UserNmae,pwd);
            //c.send sql,execute;
            stmt=connection.createStatement();
           // String sql="insert into  tb_student values('2015310012',"+"'沈天華'"+","+"'男'"+",25,"+"'黑龍江'"+",'漢','AC1302')";
            //String sql="delete from tb_student where studentNo="+"'2015310012'"+";
            String sql="select * from tb_student";
            //d.execute sql;
           // int count=stmt.executeUpdate(sql);//can only be use for: insert,delete,update;
            //f.resultset ;if the way you do it is select,you should use this method:  stmt.executeQuery(sql);
             rst=stmt.executeQuery(sql);
            //e.result of handing;
            while(rst.next()){
                String name= rst.getString("studentName");
                int age=rst.getInt("age");
                System.out.println(name+"----"+age);
            }
           /* if(count>0){
                System.out.println("successful!");
            }else {
                System.out.println("defeat!");
            }*/
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();;
        }
        finally {
            try {
                if(rst!=null)
                    rst.close();
                if (stmt!=null)
                    stmt.close();
                if(connection!=null)
                    connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    public static  void main(String[] args){
        update();
    }
}

發佈了14 篇原創文章 · 獲贊 8 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章