Java中MySQL建立连接
Java中MySQL建立连接
下面是在JAVA中与MySQL建立连接的一个模块:
- package com.han;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.SQLException;
- /**
- * SQL connection module
- * @author HAN
- *
- */
- public class Conn {
- Connection con;//Declare a Connection object
- String driver="com.mysql.jdbc.Driver";// the MySQL driver
- String url="jdbc:mysql://localhost:3306/db_jdbc";// URL points to destination database to manipulate
- String user="root";//user name for the specified database
- String pwd="hangaowen1212";//the corresponding password
- public Connection getConnection(){
- try {
- Class.forName(driver);// add MySQL driver
- System.out.println("Database driver is successfully added");
- } catch (ClassNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- try {
- con=DriverManager.getConnection(url,user,pwd);//create a connection object
- System.out.println("Database connection is successful");
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return con;
- }
- public static void main(String[] args){
- Conn c=new Conn();
- c.getConnection();
- }
- }
附:MySQL相关配置
1. 下载MySQL,安装(大小300多M)
2. 配置数据库(打开MySQL建立用户名,密码,数据库URL,端口号等);还要打开MySQL安装目录,找到mysql-connector-java-5.1.15-bin.jar这样的文件加进CLASSPATH(CMD在电脑的系统环境变量中,eclipse在run configuration中)。
评论暂时关闭