Ubuntu下使用安装和使用MYSQL和JDBC

JDBCAndMySQL

#####################################################33

1.安装MYSQL,JDBC

sudo apt install mysql-client mysql-server  libmysql-java

打开~/.bashrc文件,添加CLASSPATH,然后更新源文件,并查看环境变量设置情况。
sudo geany ~/.bashrc
    CLASSPATH = $CLASSPATH:/usr/share/java/mysql.jar
source ~/.bashrc
echo $CLASSPATH

2. 配置

#登录主用户,设置密码
mysql -uroot -p

#创建数据库
    create database webmagic;
#新增用户
    grant all privileges on webmagic.* to auss@localhost identified by "auss";
    flush privileges;

#测试新用户
mysql -uauss -h 127.0.0.1 -p

3. 在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/webmagic";

  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","auss");
    p.put("password","auss");

    // Now try to connect
    Connection c = DriverManager.getConnection(CONNECTION,p);

    System.out.println("It works !");
    c.close();
    }
}

你可能感兴趣的:(Java)