使用java連接MySQL數(shù)據(jù)庫(kù)與其他的數(shù)據(jù)庫(kù)連接核心是一樣的,如果說(shuō)區(qū)別,那就是所需的驅(qū)動(dòng)不一樣。
萬(wàn)源ssl適用于網(wǎng)站、小程序/APP、API接口等需要進(jìn)行數(shù)據(jù)傳輸應(yīng)用場(chǎng)景,ssl證書(shū)未來(lái)市場(chǎng)廣闊!成為創(chuàng)新互聯(lián)的ssl證書(shū)銷(xiāo)售渠道,可以享受市場(chǎng)價(jià)格4-6折優(yōu)惠!如果有意向歡迎電話聯(lián)系或者加微信:13518219792(備注:SSL證書(shū)合作)期待與您的合作!
工具/原料
MySQL、JDK
方法/步驟
1、首先需要安裝好JDK(配置環(huán)境變量),如圖所示:
2、其次要安裝好MySQL數(shù)據(jù)庫(kù),可以使用可視化Navicar For MySQL,如圖所示:
3、最后通過(guò)代碼進(jìn)行連接。
(1)確定連接路徑URL:
String url="jdbc:mysql://localhost(可以是本機(jī)IP地址):3306(端口號(hào))/mysqltest(數(shù)據(jù)庫(kù)名稱(chēng))?"+"user=用戶(hù)賬號(hào)password=用戶(hù)密碼useUnicode=字符編碼";
(2)加載驅(qū)動(dòng):
Class.forName("com.mysql.jdbc.Driver");
(3)連接,獲取Connection對(duì)象
Connection conn=DriverManager.getConnection(url)
(4)可以通過(guò)conn對(duì)象檢驗(yàn)連接與否。
private static String url="jdbc:oracle:thin:@localhost:1521:xe";
聲明一個(gè)字符串用于存儲(chǔ)數(shù)據(jù)庫(kù)連接信息,jdbc:oracle:thin:@localhost:1521表示你要連接的是oracle數(shù)據(jù)庫(kù)地址是本機(jī)
xe為本機(jī)數(shù)據(jù)庫(kù)庫(kù)名。
private static String driverName="oracle.jdbc.driver.OracleDriver";
這一條是聲明一個(gè)字符串存儲(chǔ)數(shù)據(jù)庫(kù)驅(qū)動(dòng)
//連接mysql,先導(dǎo)入mysql驅(qū)動(dòng)
Connection?conn;?//?聲明Connectoion對(duì)象
String?driver?=?"com.mysql.jdbc.Driver";?//?驅(qū)動(dòng)程序名
//oracle,先導(dǎo)入oracle驅(qū)動(dòng)
//Class.forName("oracle.jdbc.driver.OracleDriver");
//String?url="jdbc:oracle:this@localhost:1521:testdb ";????//中間冒號(hào)分隔
String?url?=?"jdbc:mysql://localhost:3306/testdb";?//?要訪問(wèn)的數(shù)據(jù)庫(kù)
String?user?=?"root";
String?password?=?"root";
Class.forName(driver);?//?加載驅(qū)動(dòng)
conn?=?DriverManager.getConnection(url,?user,?password);
用這個(gè)類(lèi)吧.好的話,給我加加分.
import java.sql.*;
/**
* @功能: 一個(gè)JDBC的本地化API連接類(lèi),封裝了數(shù)據(jù)操作方法,只用傳一個(gè)SQL語(yǔ)句即可
* @作者: 李開(kāi)歡
* @日期: 2007/
*/
public class ConnectionDemo {
/*
* 這里可以將常量全部放入另一個(gè)類(lèi)中,以方便修改
*/
private static Connection conn;
private static Statement ps;
private static ResultSet rs;
private static final String DRIVER = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
private static final String URL = "jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=mydb";
private static final String USER ="sa";
private static final String PASS = "sa";
public ConnectionDemo() {
// TODO Auto-generated constructor stub
ConnectionDemo.getConnection();
}
public static Connection getConnection(){
System.out.println("連接中...");
try {
Class.forName(ConnectionDemo.DRIVER);
conn = DriverManager.getConnection(ConnectionDemo.URL, ConnectionDemo.USER, ConnectionDemo.PASS);
System.out.println("成功連接");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
public static Statement getStatement(String sql){
System.out.println("執(zhí)行SQL語(yǔ)句中...");
try {
ps = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
if(sql.substring(0, 6).equals("select")){
rs = ps.executeQuery(sql);
System.out.println("執(zhí)行完查詢(xún)操作,結(jié)果已返回ResultSet集合");
}else if(sql.substring(0, 6).equals("delete")){
ps.executeUpdate(sql);
System.out.println("已執(zhí)行完畢刪除操作");
}else if(sql.substring(0, 6).equals("insert")){
ps.executeUpdate(sql);
System.out.println("已執(zhí)行完畢增加操作");
}else{
ps.executeUpdate(sql);
System.out.println("已執(zhí)行完畢更新操作");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ps;
}
public static ResultSet getResultSet(){
System.out.println("查詢(xún)結(jié)果為:");
return rs;
}
public static void closeConnection(){
System.out.println("關(guān)閉連接中...");
try {
if (rs != null) {
rs.close();
System.out.println("已關(guān)閉ResultSet");
}
if (ps != null) {
ps.close();
System.out.println("已關(guān)閉Statement");
}
if (conn != null) {
conn.close();
System.out.println("已關(guān)閉Connection");
}
} catch (Exception e) {
// TODO: handle exception
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ConnectionDemo.getConnection();
String sql = "delete from type where id = 1";
ConnectionDemo.getStatement(sql);
String sql2 = "insert into type values(1,'教學(xué)設(shè)備')";
ConnectionDemo.getStatement(sql2);
String sql1 = "select * from type";
ConnectionDemo.getStatement(sql1);
ResultSet rs = ConnectionDemo.getResultSet();
System.out.println("編號(hào) "+"類(lèi) 型");
try {
while(rs.next()){
System.out.print(" "+rs.getInt(1)+" ");
System.out.println(rs.getString(2));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ConnectionDemo.closeConnection();
}
}
import java.sql.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class inensshow extends JFrame {
private Connection connection;
private Statement statement;
private ResultSet resultSet;
private ResultSetMetaData rsMetaData;
//GUI變量定義
private JTable table;
private JTextArea inputQuery;
private JButton submitQuery;
public inensshow()
{
//Form的標(biāo)題
super( "輸入SQL語(yǔ)句,按查詢(xún)按鈕查看結(jié)果。" );
String url = "jdbc:mysql://localhost:3306/web";
String username = "inens";
String password = "inens";
//加載驅(qū)動(dòng)程序以連接數(shù)據(jù)庫(kù)
try {
Class.forName( "org.gjt.mm.mysql.Driver" );
connection = DriverManager.getConnection(
url, username, password );
}
//捕獲加載驅(qū)動(dòng)程序異常
catch ( ClassNotFoundException cnfex ) {
System.err.println(
"裝載 JDBC/ODBC 驅(qū)動(dòng)程序失敗。" );
cnfex.printStackTrace();
System.exit( 1 ); // terminate program
}
//捕獲連接數(shù)據(jù)庫(kù)異常
catch ( SQLException sqlex ) {
System.err.println( "無(wú)法連接數(shù)據(jù)庫(kù)" );
sqlex.printStackTrace();
System.exit( 1 ); // terminate program
}
//如果數(shù)據(jù)庫(kù)連接成功,則建立GUI
//SQL語(yǔ)句
String test="SELECT * FROM data";
inputQuery = new JTextArea( test, 4, 30 );
submitQuery = new JButton( "查詢(xún)" );
//Button事件
submitQuery.addActionListener(
new ActionListener() {
public void actionPerformed( ActionEvent e )
{
getTable();
}
}
);
JPanel topPanel = new JPanel();
topPanel.setLayout( new BorderLayout() );
//將"輸入查詢(xún)"編輯框布置到 "CENTER"
topPanel.add( new JScrollPane( inputQuery), BorderLayout.CENTER );
//將"提交查詢(xún)"按鈕布置到 "SOUTH"
topPanel.add( submitQuery, BorderLayout.SOUTH );
table = new JTable();
Container c = getContentPane();
c.setLayout( new BorderLayout() );
//將"topPanel"編輯框布置到 "NORTH"
c.add( topPanel, BorderLayout.NORTH );
//將"table"編輯框布置到 "CENTER"
c.add( table, BorderLayout.CENTER );
getTable();
setSize( 500, 300 );
//顯示Form
show();
}
private void getTable()
{
try {
//執(zhí)行SQL語(yǔ)句
String query = inputQuery.getText();
statement = connection.createStatement();
resultSet = statement.executeQuery( query );
//在表格中顯示查詢(xún)結(jié)果
displayResultSet( resultSet );
}
catch ( SQLException sqlex ) {
sqlex.printStackTrace();
}
}
private void displayResultSet( ResultSet rs )
throws SQLException
{
//定位到達(dá)第一條記錄
boolean moreRecords = rs.next();
//如果沒(méi)有記錄,則提示一條消息
if ( ! moreRecords ) {
JOptionPane.showMessageDialog( this,
"結(jié)果集中無(wú)記錄" );
setTitle( "無(wú)記錄顯示" );
return;
}
Vector columnHeads = new Vector();
Vector rows = new Vector();
try {
//獲取字段的名稱(chēng)
ResultSetMetaData rsmd = rs.getMetaData();
for ( int i = 1; i = rsmd.getColumnCount(); ++i )
columnHeads.addElement( rsmd.getColumnName( i ) );
//獲取記錄集
do {
rows.addElement( getNextRow( rs, rsmd ) );
} while ( rs.next() );
//在表格中顯示查詢(xún)結(jié)果
table = new JTable( rows, columnHeads );
JScrollPane scroller = new JScrollPane( table );
Container c = getContentPane();
c.remove(1);
c.add( scroller, BorderLayout.CENTER );
//刷新Table
c.validate();
}
catch ( SQLException sqlex ) {
sqlex.printStackTrace();
}
}
private Vector getNextRow( ResultSet rs,
ResultSetMetaData rsmd )
throws SQLException
{
Vector currentRow = new Vector();
for ( int i = 1; i = rsmd.getColumnCount(); ++i )
currentRow.addElement( rs.getString( i ) );
//返回一條記錄
return currentRow;
}
public void shutDown()
{
try {
//斷開(kāi)數(shù)據(jù)庫(kù)連接
connection.close();
}
catch ( SQLException sqlex ) {
System.err.println( "Unable to disconnect" );
sqlex.printStackTrace();
}
}
public static void main( String args[] )
{
final inensshow app =
new inensshow();
app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
app.shutDown();
System.exit( 0 );
}
}
);
}
}
------------------------------------------------------------
這次在WIN98中就不好使了。因?yàn)镸ysql的驅(qū)動(dòng)程序沒(méi)有也沒(méi)能加入到CLASSPATH 當(dāng)中,但是JSP卻可以使用(JSP的98驅(qū)動(dòng)加載詳見(jiàn)Jsp與Mysql連接查錯(cuò)文章),所以這次我是在XPServer中測(cè)試的。
文章名稱(chēng):數(shù)據(jù)庫(kù)連接java代碼,java中連接數(shù)據(jù)庫(kù)的代碼
網(wǎng)頁(yè)鏈接:http://jinyejixie.com/article26/hsiejg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供靜態(tài)網(wǎng)站、網(wǎng)站維護(hù)、網(wǎng)站排名、企業(yè)建站、網(wǎng)站改版、Google
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)