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();