java串連mysql資料代碼

來源:互聯網
上載者:User

java串連mysql教程資料代碼

package jxc;

import java.sql.connection;
import java.sql.drivermanager;
import java.sql.preparedstatement;
import java.sql.resultset;
import java.sql.sqlexception;
import java.sql.statement;
import java.sql.*;

public class jdbcconn {
    static connection con;
    static statement stmt;
    public static preparedstatement ps教程t;
    static resultset rs = null;

    public static void load()// 載入驅動的方法
    {
        try {
            string driver = "com.mysql.jdbc.driver";
            class.forname(driver);
        } catch (exception e) {
            system.out.println("沒有找到驅動");
        }
    }

    public static void conn()// 建立串連的方法
    {
        try {
            string url = "jdbc:mysql://localhost:3306/jxc_db?useunicode=true&characterencoding=gbk";
            string user = "root";
            string password = "xiajun";
            con = drivermanager.getconnection(url, user, password);
        } catch (exception ee) {
            system.out.println("error:沒有串連");
        }
    }

    public static void exesql()// 執行sql的方法
    {
        try {
            stmt = con.createstatement();
            // pst=(preparedstatement) con.createstatement();
            // stmt.executequery("");
            // stmt.executeupdate("");
        } catch (exception e) {

        }
    }

    public static void close()// 關閉的方法
    {
        try {
            con.close();
            // stmt.close();
            pst.close();
            // rs.close();
        } catch (sqlexception ee) {
        }
    }

    public static void close1() {
        try {
            con.close();
            stmt.close();
            // pst.close();
            rs.close();
        } catch (sqlexception ee) {
        }
    }
}

/*
載入驅動程式:

1.先找到要使用的驅動程式類的名稱:如com.mysql.jdbc.driver。可以使用命令列參數方式匯入,可以使用修改classpath方式,最好是使用匯入jar包的方式。

2.註冊驅動程式:有下列幾種方式:

1.命令列參數的方式設定jdbc.drivers屬性

2.方法調用設定系統屬性:system.setproperty("jdbc.drivers", driver); driver = "com.mysql.jdbc.driver"

3.載入驅動程式類:class.forname(driver);

4.使用屬性檔案

步驟2。開啟資料庫教程串連mysql

建立一個串連:

connection conn = drivermanager.getconnection(url, username, pwd); url:指定的資料來源,"jdbc:mysql://localhost/test"

步驟3.執行sql命令

1.建立statement對象(要使用到上一步中的串連mysql資料庫conn):

statement st = conn.createstatement(); 2.使用此對象執行語句:

st.executequery("select * from test");executeupdate(); 注意select查詢必須使用executequery();

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.