以下这段代码是java连接SQL server数据库的代码;这段代码是能成功连接到SQL server数据库的。如果现在要改为连接mysql数据库,并实现相同的功能;相应的代码该如何写?
    url1 = "jdbc:microsoft:sqlserver://" + url;
    url = "jdbc:microsoft:sqlserver://" + url + ";DatabaseName=" + database.getText();
    driver = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
    String sql = "select name from sysdatabases where name='" + database.getText() + "'";
    CustomCodePanel.customCodePanelProxy.setVariable("$FlowIndependent_DB_Type$", "SQL Server");
    Class.forName(driver).newInstance();
    conn = DriverManager.getConnection(url1, user, password);
    Statement stm = conn.createStatement();
    ResultSet rs = stm.executeQuery(sql);
    if(rs.next()){
   CustomCodePanel.customCodePanelProxy.setVariable("$FlowIndependent_DB_Exist$", "YES");
   CustomCodePanel.customCodePanelProxy.setVariable("$FlowIndependent_DB_Initial$", "");
   }else {
   CustomCodePanel.customCodePanelProxy.setVariable("$FlowIndependent_DB_Exist$", "NO");
  CustomCodePanel.customCodePanelProxy.setVariable("$FlowIndependent_DB_Initial$", "yes");
 stm.execute("IF DB_ID('" + database.getText() + "') IS NULL BEGIN Create DATABASE " + '"'+ database.getText() + '"' + " END");}
    conn = DriverManager.getConnection(url, user, password);
    rs.close();
    stm.close();
    conn.close();
下面这段代码是我自己实现的连接mysql数据库的代码,但连接失败。有高手知道是什么原因吗?
url = "jdbc:mysql://"+SVAddress.getText()+":"+port+"/"+database.getText();
driver = "org.gjt.mm.mysql.Driver";
String sql ="select SCHEMA_NAME FROM information_schema.SCHEMATA where SCHEMA_NAME='"+database.getText()+"'";
CustomCodePanel.customCodePanelProxy.setVariable("$FlowIndependent_DB_Type$", "mysql");
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url,user,password);
Statement stm = conn.createStatement();
ResultSet rs = stm.executeQuery(sql);
if(rs.next()){
 CustomCodePanel.customCodePanelProxy.setVariable("$FlowIndependent_DB_Exist$", "YES");
 CustomCodePanel.customCodePanelProxy.setVariable("$FlowIndependent_DB_Initial$", "");
 } else{
 CustomCodePanel.customCodePanelProxy.setVariable("$FlowIndependent_DB_Exist$", "NO");
 CustomCodePanel.customCodePanelProxy.setVariable("$FlowIndependent_DB_Initial$", "yes");
 stm.execute(" CREATE DATABASE IF NOT EXISTS"+ database.getText()); }
rs.close();
stm.close();
conn.close();

解决方案 »

  1.   

    驱动可以到
    http://dev.mysql.com/downloads/#connector-j
    下载
      

  2.   

    连接失败 ?驱动安装是否正确?url = "jdbc:mysql://"+SVAddress.getText()+":"+port+"/"+database.getText();
    的内容是什么,调试中打出来看一下。一般格式是这样
    conn = 
           DriverManager.getConnection("jdbc:mysql://localhost/test?" + 
                                       "user=monty&password=greatsqldb");
    
      

  3.   

    1,mysql和sqlserver驱动不同
    2,端口不同
    3,Class.forName(driver).newInstance(); 你这句根本不是把mysql的驱动加载到内存,而只是new了一个对象而已
    似乎可以如下写法
     Class.forName("com.mysql.jdbc.Driver");来加载驱动