[教學] java JDBC and MySQL on Ubuntu

看板java作者 (小惡魔)時間17年前 (2008/11/15 21:37), 編輯推噓2(201)
留言3則, 2人參與, 最新討論串1/2 (看更多)
原文:http://blog.wu-boy.com/2008/11/15/597/ 1. 首先先安裝 deb 檔案:透過 apt-get 的方式 # # 首先尋找 java lib with mysql apt-get install libmysql-java 2. 安裝好之後尋找 jar 檔案,加入到 class path 裡面 # # 首先 echo $CLASSPAT # # java mysql jar 檔案如下 /usr/share/java/mysql.jar # 加入 CLASSPATH,修改 /etc/bash.bashrc export CLASSPATH=$CLASSPATH:/usr/share/java/mysql.jar # 然後在 source /etc/bash.bashrc 3. 底下用 java 程式測試一下 import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class MainClass { public static Connection getConnection() throws Exception { // Load the JDBC driver String driver = "com.mysql.jdbc.Driver"; //String driver = "org.gjt.mm.mysql.Driver"; Class.forName(driver); // Create a connection to the database String url = "jdbc:mysql://ip:3306/NIBS?userUnicode=true"; String username = "XXXXX"; String password = "XXXXX"; return DriverManager.getConnection(url, username, password); } public static void main(String args[]) { Connection conn = null; Statement stmt = null; ResultSet rs = null; int a = 1; try { conn = getConnection(); stmt = conn.createStatement(); String query = "SET NAMES 'utf8'"; rs = stmt.executeQuery(query); query = "INSERT test (test1, test2) values ('測試','測試')"; a = stmt.executeUpdate(query); query = "select * from project_users"; rs = stmt.executeQuery(query); while (rs.next()) { System.out.println(rs.getString("username") + " " + rs.getString("user_real_name") + " "+ rs.getString("user_ether_ip")); } } catch (Exception e) { // handle the exception e.printStackTrace(); System.err.println(e.getMessage()); } finally { try { rs.close(); stmt.close(); conn.close(); } catch (Exception ee) { ee.printStackTrace(); } } } } 如果中文有問題,可以修改 mysql 設定 my.cnf [client] [mysqld] 都加上 default-character-set = utf8 這樣就可以了 原文:http://blog.wu-boy.com/2008/11/15/597/ -- Appleboy Blog: http://blog.Wu-Boy.com Appleboy Life: http://life.wu-boy.com -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.123.107.20

11/15 22:06, , 1F
只有第一步和 linux 有關 orz
11/15 22:06, 1F

11/15 22:07, , 2F
第二步怪怪的, 比較好奇有需要改全域設定嗎@@?
11/15 22:07, 2F

11/15 23:33, , 3F
方便其他使用者使用 XD
11/15 23:33, 3F
※ 編輯: appleboy46 來自: 140.123.216.193 (11/15 23:34)
文章代碼(AID): #197j2lcF (java)
文章代碼(AID): #197j2lcF (java)