天天看點

netBeans如何連接配接mysql

轉載自:NetBeans中配合java通路資料庫 

1.首先添加資料庫包引用:項目->庫,右鍵->添加庫,在可用庫清單裡找到mysql jdbc 驅動程式,點選添加庫按鈕即可。

netBeans如何連接配接mysql

2.配置連接配接mysql資料庫

我通路的是本地伺服器上的mysql資料庫,首先對mysql資料庫進行配置。服務->資料庫->驅動程式->mysql (connector/j driver),右鍵->連接配接設定,彈出如下界面進行配置(記得把資料庫這個選項改成自己想要連接配接的資料庫名字):

netBeans如何連接配接mysql

3、java通路資料庫

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.logging.Level;
import java.util.logging.Logger;

public class JDBCTest {
    public static void main(String[] args) {
        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            Connection  conn = (Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306/databasename", "user", "password");
            Statement stmt   = (Statement) conn.createStatement();
            //上面的databasename,user,password都要自己改;下面是我的例子,你可以照着自己改
           
ResultSet result = (ResultSet) stmt.executeQuery("select id from person_info");
            while(result.next()){
                System.out.println(result.getString("id"));
            }
        } catch (Exception ex) {
            Logger.getLogger(JDBCTest.class.getName()).log(Level.SEVERE, null, ex);
        }
            
       
    }
}