2014-01-30 191 views
-2

我想将我的Java应用程序连接到MySql服务器。连接MySQL数据库Java

在NetBeans中我使用这些字符串:

String url = "jdbc:derby://localhost:1527/Oratorio"; 

    try { 
     Class.forName("org.apache.derby.jdbc.ClientDriver"); //... Carica il Driver 
     con = DriverManager.getConnection(url); 
     stmt = con.createStatement(); 

但是,如果我建立这个程序它不连接到数据库。

有人可以帮助我吗?

感谢

+0

此代码会让我的大脑受伤。 – AWT

回答

4

如果您尝试连接到使用Derby连接MySQL数据库,你是不会成功的。

您需要使用可以实际连接到数据库的连接器。

+0

你能举个例子吗?谢谢 – Carioni

+2

https://www.google.com/search?q=java+mysql – SLaks

0

您需要添加MySQL连接器JAR,然后您可以像这样连接,它只是一个片段! URL,用户名和密码与用户名/密码Stringconstants用于访问DB和URL是像 “JDBC:MySQL的://本地主机:3306/< 'DB_NAME'>”

[...]

try { 
Driver driver = (Driver) Class.forName("com.mysql.jdbc.Driver").newInstance(); DriverManager.registerDriver(driver); 
connection = DriverManager.getConnection(URL, USERNAME, PASSWORD); 

也许这会有所帮助。

0

那么我有一个学校项目,我不得不使用MySQL(这是一个问答游戏)。我创建了一个SQLHandler类,它非常通用,您可以在每个项目中使用它,其中包括jdbc mysql连接器,可以从here下载。我下载了平台独立版本,这是一个jar文件。随意使用下面的代码:

import java.sql.*; 

public class SQLHandler { 
private String host; 
private String port; 
private String db; 
private String user; 
private String pw; 
public SQLHandler(String host,String port, String db, String user,String pw){ 
    this.host=host; 
    this.port=port; 
    this.db=db; 
    this.user=user; 
    this.pw=pw; 
    try { 
     Class.forName("com.mysql.jdbc.Driver"); 
    } catch (ClassNotFoundException e) { 
     e.printStackTrace(); 
    } 
} 
public String getHost(){ 
    return host; 
} 
public String getPort(){ 
    return port; 
} 
public String getDb(){ 
    return db; 
} 
public String getPw(){ 
    return pw; 
} 
public String getUser(){ 
    return user; 
} 
public String URLConfig(String host, String port, String dbaseName){ 
    String url="jdbc:mysql://"+host+":"+port+"/"+dbaseName; 
    return url; 
} 
public void inputQuery(String command) throws SQLException{ 
    String url=URLConfig(getHost(),getPort(),getDb()); 
    Connection conn=DriverManager.getConnection(url,getUser(),getPw()); 
    PreparedStatement query=conn.prepareStatement(command); 
    query.executeUpdate(command); 
} 
public String outputQuery(String command,int cnum)throws SQLException{ //cnum defines the number of columns in your table 
    String url=URLConfig(getHost(),getPort(),getDb()); 
    Connection conn=DriverManager.getConnection(url,getUser(),getPw()); 

    PreparedStatement query=conn.prepareStatement(parancs); 
    ResultSet result=query.executeQuery(parancs); 
    String res=""; 
    while(result.next()){ 
     for(int i=1; i<=cnum; i++){ 
      res=res+result.getString(i)+" "; 
     } 
    } 
    return res; 
} 

}

我希望它会帮助你的!