2012-10-12 41 views
-3

我有在連接到MySQL數據庫的時候我用這code.I問題已經檢查該端口號是3128.So沒有關於that.I問題檢查它,我認爲問題出在使用Java獲取連接到mysql數據庫?

connection= DriverManager.getConnection("jdbc:mysql://localhost:3128/gcc","root", "root"); 

編譯時沒有錯誤。有人可以幫我解決這個問題嗎?

import java.awt.*; 
import java.applet.*; 
import java.awt.event.*; 
import java.sql.*; 
//import java.net.*; 

public class Main extends Applet implements ActionListener 
{ 
TextArea tarea; 
Button bsubmit; 

public void init() 
{ 
    setBackground(new Color(0,0,0)); 
    setForeground(Color.white); 

    Label l1=new Label("Write your code : "); 
    l1.setFont(new Font("lucida console",Font.PLAIN,25)); 
    l1.setSize(200,30); 

    tarea=new TextArea(); 
    tarea.setFont(new Font("lucida console",Font.PLAIN,18)); 
    tarea.setForeground(new Color(0,0,0)); 
    tarea.setSize(600,250); 

    bsubmit=new Button("Submit"); 
    bsubmit.setFont(new Font("lucida console",Font.PLAIN,15)); 
    bsubmit.setBackground(new Color(255,255,255)); 
    bsubmit.setForeground(new Color(0,0,0)); 
    bsubmit.setSize(100,30); 

    add(l1); 
    add(tarea); 
    add(bsubmit); 

    setLayout(null); 
    l1.setLocation(40,40); 
    tarea.setLocation(40,100); 
    bsubmit.setLocation(40,400); 

    bsubmit.addActionListener(this); 
} 

public void actionPerformed(ActionEvent ae) 
{ 
    if(ae.getSource()==bsubmit) 
    { 
    Connection connection=null; 
    try 
    { 
    Class.forName("com.mysql.jdbc.Driver"); 
    connection= DriverManager.getConnection("jdbc:mysql://localhost:3128/gcc","root", "root"); 
    Statement stmt = connection.createStatement(); 
    stmt.executeUpdate("CREATE TABLE test2 (code VARCHAR(254))"); 
    } 
    catch (Exception e) {} 
    } 
} 
} 
+4

有什麼樣的問題?它超時了?沒有權限?拒絕訪問? –

+3

如果將'jdbc:mysql:// localhost:3128/gcc'更改爲'jdbc:mysql://127.0.0.1:3128/gcc',它會工作嗎?您還應該在catch塊中打印異常消息,以便查看發生了什麼錯誤。 – drew010

+7

一個空的catch塊是你可以對自己做的最糟糕的事情之一。爲了好心,打印堆棧跟蹤。檢查是否可以使用MySQL管理員訪問該數據庫。如果它不能,那麼Java就不太可能。爲什麼要使用標準3306以外的任何端口?你通過改變完成了什麼? – duffymo

回答

0

Java數據庫驅動程序是最糟糕的事情。我記得,我有我的第一個JDBC驅動程序(或者讓我們說:一個工作事務;)在「僅」2天內安裝,並且我知道一個有兩週時間的人,哈哈。

在大多數情況下,最後一個問題是SQL問題。因爲您需要將用戶權限設爲「用戶名」@「IP」。您可以在表user_privileges中的數據庫information_schema中找到用戶信息。有足夠的教程如何處理它們,但我喜歡'username'@'%'以獲得測試環境中的所有特權。 微笑

這可能會幫助您:http://dev.mysql.com/doc/refman/5.1/de/adding-users.html

呀,那些該死的SQL的權利...; d

@Luiggi:那是肯定沒有愚蠢的問題!我有幾個小時才能發現這一點!我的意思是,初學者知道Java sql類只有xxxxxxx接口,沒有實現代碼?! %d

編輯

不管怎樣:

Class.forName("...driverblabla..."); 

這是否行代碼看起來像Java? Nooo,它的一個xxxxxx編譯器破解或任何!但它的作品,它確實做了什麼!

哦,不過對於某些驅動程序實現,這將無法正常工作,你需要這樣的:

Class.forName("...driverblabla...").newInstance(); 

LMAO!

@Abhinav:添加此行您的getConnection線以上:

Class.forName("com.mysql.jdbc.driver").newInstance(); 

不要去想它究竟一秒(我知道,但是...讓我們擰;)