导入驱动包:
链接:https://pan.baidu.com/s/1RGvpXLW7ZvcDX1DpoqLuIg
提取码:t2ee
复制这段内容后打开百度网盘手机App,操作更方便哦
1.连接数据库
package com.conn;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBC {
//驱动
final static String driver = "com.mysql.jdbc.Driver";
//连接数据库的地址
final static String url = "jdbc:mysql://127.0.0.1:3306/db_test?useUnicode=true&characterEncoding=utf-8";
//数据库用户名
final static String username = "root";
//数据库密码
final static String password = "123456";
//建立数据库连接
static{
try {
//加载驱动
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//建立连接
public static Connection getConnection() {
Connection conn = null;
try {
//通过DriverManager获取到数据库连接
conn = DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
//释放资源
public static void close(Connection conn,Statement st,ResultSet rs) throws SQLException {
if (conn != null) {
conn.close();
}
if (st != null) {
st.close();
}
if (rs != null) {
rs.close();
}
}
//测试连接数据库是否成功
public static void main(String[] args) {
System.out.println(JDBC.getConnection());
}
}
2.创建表
CREATE TABLE user (
id int(11) NOT NULL AUTO_INCREMENT,
usernam` varchar(64) DEFAULT NULL,
password varchar(64) DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
/*Data for the table `user` */
insert into `user`(`id`