使用Java连接到数据库 [英] Connecting to database using java

查看:113
本文介绍了使用Java连接到数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚安装了mysql服务器5和NetBeans 7.1

我想知道如何使用Java连接到mysql服务器上的数据库

这是我在网上找到的代码

i have just installed mysql server 5 and NetBeans 7.1

i want to know how to use java to connect to database on mysql server

it is a code i found on net

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package database_con;
import java.sql.*;
/**
 *
 * @author engamir
 */
public class Database_con {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        System.out.println("MySQL Connect Example.");
        Connection conn = null;
        String url = "jdbc:mysql://localhost:3306/";
        String dbName = "test";
        String driver = "com.mysql.jdbc.Driver";
        String userName = "root"; 
        String password = "globalamirtarek";
        try
        {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            conn = DriverManager.getConnection(url+dbName,userName,password);
            System.out.println("Connected to the database");
            conn.close();
            System.out.println("Disconnected from database");
        } 
        catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException e) 
        {
            System.out.println(e.getMessage());
        }
    }
}



此代码使用ClassNotFoundException进入陷阱

我可以在Netbeans上的服务下的驱动程序"列表下找到该驱动程序,并且可以使用它连接到mysql数据库



this code enter the catch with ClassNotFoundException

i can find this Driver under Drivers list under services on Netbeans and i can connect using it to the mysql database

can any one tell me if i make something wrong?

推荐答案

看起来很自然.

当您收到ClassNotFound异常时-找不到哪个类?

请确保所有部分都在构建中:

在Netbeans中配置构建 [
looks good spontaneous.

When you get a ClassNotFound Exception - which class is not found?

Please make sure that all parts are in the build:

Configuring the build in Netbeans[^]


这篇关于使用Java连接到数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆