|
JDBC And MYSQL
1.介绍:
本文介绍如何设置java应用程序与mysql数据库进行通信。
MYSQL JDBC驱动包下载:http://dev.mysql.com/downloads/connector/j/
2.安装:
安装MYSQL客户端,服务器和JDBC连接器,可以通过使用下面:
- sudo apt-get install mysql-server
- sudo apt-get install mysql-client
- sudo apt-get install libmysql-java
3.设置Mysql
设置密码为root用户或是任何你想要的。
- mysqladmin -u root password root
检查你能够连接数据库mysql:
之后键入你的密码;
4.创建SQL 数据库和表
创建一个数据库和表,例如:
- create database emotherearth;
5.Eclipse
运行Eclipse时,可能会有“Class Not Found”异常,解决的办法是:
go to:Project -> Properties -> java Build Path -> Libraries tab
Then select 'Add External JARs', 找到'/usr/share/java/mysql-connector-java-*-bin.jar添加到Eclipse中;
6.设置用户使用的JDBC
在/home/[user]/.bashrc文件中,添加如下内容:
- CLASSPATH=$CLASSPATH:/usr/share/java/mysql.jar
- export CLASSPATH
你也可以设置所有用户,编辑/etc/environment(用 sudo vi /etc/environment)
- CLASSPATH=".:/usr/share/java/mysql.jar"
撤销再次登录,在终端输入:
echo $CLASSPATH
你会看到打印出来你的CLASSPATH,其中含有:":/usr/share/java/mysql.jar" ;
7.通过上面在测试时还会报错:
还需要将mysql-connector-java-*-bin.jar复制到tomcat目录下的lib文件夹中,如果tomcat已经是开启状态,需要重启tomcat才能生效。
8.测试:(Test in Java)
- import java.sql.*;
- import java.util.Properties;
- public class DBDemo
- {
- // The JDBC Connector Class.
- private static final String dbClassName = "com.mysql.jdbc.Driver";
- // Connection string. emotherearth is the database the program
- // is connecting to. You can include user and password after this
- // by adding (say) ?user=paulr&password=paulr. Not recommended!
- private static final String CONNECTION =
- "jdbc:mysql://127.0.0.1/emotherearth";
- public static void main(String[ args) throws
- ClassNotFoundException,SQLException
- {
- System.out.println(dbClassName);
- // Class.forName(xxx) loads the jdbc classes and
- // creates a drivermanager class factory
- Class.forName(dbClassName);
- // Properties for user and password. Here the user and password are both 'paulr'
- Properties p = new Properties();
- p.put("user","paulr");
- p.put("password","paulr");
- // Now try to connect
- Connection c = DriverManager.getConnection(CONNECTION,p);
- System.out.println("It works !");
- c.close();
- }
- }
测试结果:
com.mysql.jdbc.Driver
It works !
附图:
|
|