java+maven+mysql(docker)
2018-02-22 本文已影响55人
heliping_peter
mysql --docker
- 下载docker,配置用户权限
sudo usermod -aG docker your_username
- 拉取mysql镜像并启动
docker run -d --name mysqltest -v ${pwd}/mysql:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=123456 -p 3306:3306 daocloud.io/library/mysql
- 进入mysql容器并添加数据表和记录
doker exec -it mysqltest sh
mysql -uroot -p123456
create database EXAMPLE;
use EXAMPLE;
create table students(
id int unsigned not null auto_increment primary key,
name char(8) not null,
sex char(4) not null,
age tinyint unsigned not null,
tel char(13) null default "-");
insert into students (name, sex, age) values("xie", "m", 21);
maven
- 新建maven工程
在pom.xml中添加依赖
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.19</version>
</dependency>
</dependencies>
源码
- 连接数据库,并获取记录
import java.sql.*;
public class mysqltest {
// JDBC驱动器名称和数据库地址
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
// 数据库的名称为EXAMPLE
static final String DB_URL = "jdbc:mysql://192.168.56.201:3306/EXAMPLE";
// 数据库用户和密码
static final String USER = "root";
static final String PASS = "123456";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
//注册JDBC 驱动程序
Class.forName("com.mysql.jdbc.Driver");
//打开连接
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
//执行查询
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, name, age FROM students";
ResultSet rs = stmt.executeQuery(sql);
//得到和处理结果集
while (rs.next()) {
//检索
int id = rs.getInt("id");
int age = rs.getInt("age");
String name = rs.getString("name");
//显示
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", Name: " + name);
System.out.println();
}
//清理环境
rs.close();
stmt.close();
conn.close();
} catch (SQLException se) {
// JDBC 操作错误
se.printStackTrace();
} catch (Exception e) {
// Class.forName 错误
e.printStackTrace();
} finally {
//这里一般用来关闭资源的
try {
if (stmt != null)
stmt.close();
} catch (SQLException se2) {
}
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}