jdbc 驱动设置

/**
* JDBC
* 2017-5-10
* HZ for test
**/

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/** import java.sql.*; **/

public class JDBC_Test
{
    static Connection conn;
    static Statement st;
    public static void main(String[] args)
    {
        insert();
    }
    public static void insert()
    {
        conn=JDBC_Test.getConnection();
        try
        {
            String sql="Insert INTO tb_user(username,sex,email)"+"VALUES('Tom','male','ahdgjs')";
            st=(Statement)conn.createStatement();
            int count=st.executeUpdate(sql);
            System.out.println("insert---"+count+"record");
            conn.close();
        }
        catch(SQLException e)
        {
            System.out.println("insert  failed"+e.getMessage());
        }


    }
    public static Connection getConnection()
    {
        Connection con;
        try
        {
            System.out.println("heng!");
            Class.forName("com.mysql.jdbc.Driver");
            System.out.println("heng!");
            con=DriverManager.getConnection("jdbc:mysql://localhost:3306/db_database04","root","123456");
            System.out.println("heng!");
            return con;
        }
        catch(Exception e)
        {
            System.out.println("connection failed    "+e.getMessage());

        }
        return null;
    }
}

【代码参考于大神】

连接数据库的部分。我写了三行测试:

因为卡在这里。根据提示信息,是驱动加载出问题。因为我根本没有download驱动。

所以download驱动。贴上链接:

链接: http://pan.baidu.com/s/1slDDW7r 密码: mbe2

下载后,建一个文件夹存放。

设置环境变量。classpath:

如果这些都做了。还是不行。重启电脑。

在连接之前,需要先启动mysql。

耶!成功鸟~

另:需要先启动数据库服务再运行程序。

原文地址:https://www.cnblogs.com/zhenzhenhuang/p/6836355.html