1、首先安装mysql客户端、服务器以及jdbc connector
sudo apt-get install mysql-server
sudo apt-get install mysql-client
sudo apt-get install libmysql-java
2、数据库相关配置
包括用户名、密码、数据库及权限什么的,这里不详细说明
3、设置用户使用JDBC
CLASSPATH=$CLASSPATH:/usr/share/java/mysql.jar
export CLASSPATH
这种方式只对当前用户有效,为使其适用于所有用户可以如下操作:
sudo vi /etc/environment
CLASSPATH=".:/usr/share/java/mysql.jar"
重新登录
echo $CLASSPATH
应该显示的是类似于":/usr/share/java/mysql.jar"
4、测试一下
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();
}
}
注意:如果你是在eclipse中有类似与“Class not found”之类的错误的话,可以将/usr/share/java/mysql-connector-java.jar加入Library