手机版
你好,游客 登录 注册
背景:
阅读新闻

Java中MySQL建立连接

[日期:2012-01-30] 来源:Linux社区  作者:gaowen_han [字体:大 中 小]

下面是在Java中与MySQL建立连接的一个模块:

[java]
  1. package com.han;  
  2.   
  3. import java.sql.Connection;  
  4. import java.sql.DriverManager;  
  5. import java.sql.SQLException;  
  6.   
  7. /** 
  8.  * SQL connection module 
  9.  * @author HAN 
  10.  * 
  11.  */  
  12. public class Conn {  
  13.     Connection con;//Declare a Connection object   
  14.     String driver="com.mysql.jdbc.Driver";// the MySQL driver   
  15.     String url="jdbc:mysql://localhost:3306/db_jdbc";// URL points to destination database to manipulate  
  16.     String user="root";//user name for the specified database   
  17.     String pwd="hangaowen1212";//the corresponding password   
  18.     public Connection getConnection(){  
  19.         try {  
  20.             Class.forName(driver);// add MySQL driver   
  21.             System.out.println("Database driver is successfully added");  
  22.         } catch (ClassNotFoundException e) {  
  23.             // TODO Auto-generated catch block   
  24.             e.printStackTrace();  
  25.         }  
  26.         try {  
  27.             con=DriverManager.getConnection(url,user,pwd);//create a connection object   
  28.             System.out.println("Database connection is successful");  
  29.         } catch (SQLException e) {  
  30.             // TODO Auto-generated catch block   
  31.             e.printStackTrace();  
  32.         }  
  33.         return con;  
  34.     }  
  35.     public static void main(String[] args){  
  36.         Conn c=new Conn();  
  37.         c.getConnection();  
  38.     }  
  39. }  

附:MySQL相关配置

1. 下载MySQL,安装(大小300多M)

2. 配置数据库(打开MySQL建立用户名,密码,数据库URL,端口号等);还要打开MySQL安装目录,找到mysql-connector-java-5.1.15-bin.jar这样的文件加进CLASSPATH(CMD在电脑的系统环境变量中,eclipse在run configuration中)。

linux
相关资讯       MySQL教程  Java教程 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款