JDBC串連MySQL資料庫的範例程式碼

來源:互聯網
上載者:User

標籤:password   exe   host   地址   pre   成功   否則   對象   otf   

雖然老調,但有時也需要用一下,從網上找的原型修改了下放這。

import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;import java.sql.Statement;import java.text.MessageFormat;public class JDBCTest { public static void main(String[] args) { Connection conn = null;// conn用於串連資料庫 Statement stmt = null;// stmt用於發送sql語句到資料庫並執行sql語句 // localhost:表示資料庫伺服器地址,如192.168.0.1 // 3306表示連接埠號碼 // test是資料庫名稱 // user是資料庫使用者名稱 // password是資料庫的密碼 String connectionString = "jdbc:mysql://192.168.35.130:3306/gllry?user=root&password=12345&useUnicode=true&characterEncoding=UTF-8"; try { // 將資料驅動程式類載入到記憶體中 Class.forName("com.mysql.jdbc.Driver").newInstance(); // 通過驅動程式管理器DriverManager擷取連線物件conn,conn已連線的服務器和資料庫資訊在connectionString conn = DriverManager.getConnection(connectionString); stmt = conn.createStatement(); StringBuilder sb = new StringBuilder(); sb.append(" insert into file ("); sb.append(" name,"); sb.append(" path, "); sb.append(" type, "); sb.append(" ownerid, "); sb.append(" addtime "); sb.append(" ) values ("); sb.append(" ‘‘{0}‘‘,"); sb.append(" ‘‘{1}‘‘,"); sb.append(" ‘‘{2}‘‘,"); sb.append(" ‘‘{3}‘‘, "); sb.append(" ‘‘{4}‘‘ "); sb.append(" )"); String result = sb.toString(); Object[] arr = { "test","test","test","0",DateTimeUtil.getCurrDateTime()}; String sql = MessageFormat.format(result, arr); // 將sql語句發送到test資料中,並執行,i是影響的行數 >0表示成功 否則表示失敗 int i = stmt.executeUpdate(sql); if (i == 1) { System.out.println("添加成功"); } else { System.out.println("添加失敗"); } } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } }}

留此以備查。

JDBC串連MySQL資料庫的範例程式碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.