目录
一、eclipse创建动态web项目
二、连接数据库
一、eclipse创建动态web项目
1.1 切换java ee
1.2 创建项目
1.3 拷贝引入jar包
资源jar包链接:https://pan.baidu.com/s/1QLIcOFNhcD8ucafFEQdvcw 提取码:mz8u
二、连接数据库
2.1 连接方法编写
在前文中,已经创建了数据库:JAVA2103 且默认端口3306,用户名root ,密码root,编码方式UTF-8.
所以连接的url如下:
jdbc:mysql://localhost:3306/JAVA2103?serverTimezone=GMT%2B8&characterEncoding=UTF-8&useSSL=true&allowMultiQueries=true
连接步骤:
(1)加载驱动 Class.forName("驱动全额类名"); //类加载:将类的class文件读取到JVM的内存中的过程
驱动:数据库厂商实现了javaJDBC接口的产物--数据库说明中查询。
(2) Connection connection = DriverManager.getConnection(url, user, password);
public Connection getConnection() {
Connection connection = null;
try {
//加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//得到数据库的链接,数据库链接--url
String url = "jdbc:mysql://localhost:3306/JAVA2103?serverTimezone=GMT%2B8&characterEncoding=UTF-8&useSSL=true&allowMultiQueries=true";
String user = "root"; //用户名
String password = "root"; //密码
connection = DriverManager.getConnection(url, user, password);
//System.out.println(connection);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return connection;
}
2.2 连接数据库的方法
Statement 是 Java 执行数据库操作的一个重要接口,用于在已经建立数据库连接的基础上,向数据库发送要执行的SQL语句。
Statement对象,用于执行静态SQL语句的CURD、不带参数的简单SQL语句。
Statement.execute(sql)--执行Select、Insert、Update、Delete的sql语句,执行select返回true,否则返回fales
Statement.executeUpdate(sql)--执行Insert、Update、Delete的sql语句,返回一个int--受影响的行数--常用
Statement.executeQuery(sql)--执行Select的sql语句,返回结果集对象--常用
ResultSet resultSet = statement.executeQuery(sql); //接收结果
2.3 实例:(数据库已存在相应的表,参考数据库学习笔记02)
测试Statement.executeUpdate(sql)、Statement.executeQuery(sql)
//通过Statement对象执行CUD--create、update、delete
public void test02() {
Connection connection = getConnection(); //得到数据库链接
Statement statement = null;
//Statement用于在已经建立数据库连接的基础上,向数据库发送要执行的SQL语句。
if(connection!=null) {
try {
//通过链接生成Statement对象
statement = connection.createStatement();
//executeUpdate()--执行Update、Insert、Delete的sql语句
//sql语句
String sql="INSERT INTO TB_USER(USER_NAME,USER_AGE,USER_BIRTHDAY) VALUES('张三',21,'2020-4-2')";
int t = statement.executeUpdate(sql); //获得执行代码后的状态参数
System.out.println("受影响的行数:"+t); //受影响的行数:1
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {//关闭非null资源
if(statement!=null)statement.close();
if(connection!=null)connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
//executeQuery(sql)--查询
public void test03() {
Connection connection = getConnection();
Statement statement = null;
ResultSet resultSet = null; //接收结果
if(connection!=null) {
try {
statement = connection.createStatement();
//查询语句
String sql="SELECT ROW_ID,USER_NAME,USER_AGE,USER_BIRTHDAY FROM TB_USER;";
resultSet = statement.executeQuery(sql); //获得结果集对象
//遍历resultSet
//.next()-向后移动一位,判断是否还有下一个对象,有--返回true,没有--返回false
while(resultSet.next()) {
//通过使用 查询SQL语句中的(column)字段顺序得到结果集中的数据
//sql下标从1开始
//long rowid = resultSet.getLong(1); //下标可能错误,不推荐使用
//通过使用 查询SQL语句中的(column)字段标签得到结果集中的数据
long rowId = resultSet.getLong("ROW_ID"); //通过字段查询,推荐使用
String userName = resultSet.getString("USER_NAME");
int userAge = resultSet.getInt("USER_AGE");
System.out.println("rowId:"+rowId);
System.out.println("userName:"+userName);
System.out.println("userAge:"+userAge);
//日期特殊--涉及数据库,使用java.sql.Date,否则正常使用java.util.Date
//java.util.Date是java.sql.Date的父类,子类自动转父类
Date userBirthday = resultSet.getDate("USER_BIRTHDAY");
System.out.println("USER_BIRTHDAY:"+userBirthday);
//使用类对象接收
//User user = new User();
//user.setRowId(resultSet.getLong("ROW_ID"));
//user.setUserName(resultSet.getString("USER_NAME"));
//System.out.println("使用类对象接收:"+user.getRowId()+" "+user.getUserName());
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {//关闭非null资源
if(statement!=null)statement.close();
if(connection!=null)connection.close();
if(resultSet!=null)resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
三、工具类编写1
此工具类:执行SQL静态语句,实现连接数据库、增删改查
其中jdbc.properties文件内容如下:
db.driverClass=com.mysql.cj.jdbc.Driver
db.jdbcUrl=jdbc:mysql://localhost:3306/JAVA2103?serverTimezone=GMT%2B8&characterEncoding=UTF-8&useSSL=true&allowMultiQueries=true
db.username=root
db.password=root
public class DBUtil {
private static final String DIVERCLASS;
private static final String DBURL;
private static final String USERNAME;
private static final String PASSWORD;
static { //静态块,自动加载
Properties properties = new Properties();
//得到类的Class对象
Class<?> clazzClass = DBUtil.class;
//根据当前类得到其ClassLoader实例--类加载
ClassLoader classLoader = clazzClass.getClassLoader();
//将classes下面的文件读成流
InputStream inputStream = classLoader.getResourceAsStream("jdbc.properties"); //数据库JAVA2103
try {
properties.load(inputStream);
//将流中的数据读取到properties对象
} catch (IOException e) {
e.printStackTrace();
}finally {
try {//关闭流
if(inputStream!=null)inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//从properties文件根据key获得值
DIVERCLASS = properties.getProperty("db.driverClass");
DBURL = properties.getProperty("db.jdbcUrl");
USERNAME = properties.getProperty("db.username");
PASSWORD = properties.getProperty("db.password");
}
//。根据jdbc.properties文件获得Connection实例,并返回
public static Connection getConnection() {
Connection connection = null;
try {
Class.forName(DIVERCLASS);
connection = DriverManager.getConnection(DBURL, USERNAME, PASSWORD);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return connection;
}
/**
* #用于执行SQL语句Insert、delete、update
* #返回一个int数据,为影响的行数
*/
public static int executeUpdate(String sql) {
Connection connection = getConnection(); //得到连接
if (connection!=null) {
Statement statement = null;
//Statement用于在已经建立数据库连接的基础上,向数据库发送要执行的SQL语句。
try {
statement = connection.createStatement(); //通过链接生成Statement对象
int result = statement.executeUpdate(sql); //执行sal语句
return result;
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {//关闭资源
if(statement!=null)statement.close();
if(connection!=null)connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return 0;
}
/**
* #查询并显示结果
* #sql语句书写要求,(查询字段之间使用逗号隔开,字段前为SELECT[空格] ,字段前为 [空格]FROM )
* #如:SELECT ROW_ID,USER_NAME,USER_AGE,USER_BIRTHDAY FROM TB_USER
* @param sql
*/
public static void executeQuery(String sql) {
Connection connection = getConnection(); //得到连接
if (connection!=null) {
Statement statement = null;
//Statement用于在已经建立数据库连接的基础上,向数据库发送要执行的SQL语句。
ResultSet resultSet = null;
//ResultSet用于接收查询的结果
//解析sql语句,获得查询的字段名
String[] arraysString=sql.split(" "); //。获得按空格分开的字符串数组
arraysString = arraysString[1].split(","); //。按逗号分开,获得查询字段名的数组
try {
statement = connection.createStatement(); //通过链接生成Statement对象
resultSet=statement.executeQuery(sql); //执行sql语句,获得查询结果
//if(resultSet!=null)System.out.println("查询成功");
while (resultSet.next()) {
int index = 0; //用于遍历字段名数组的下标,初始化为0
for (int i = 0; i < arraysString.length; i++) {
System.out.println(resultSet.getObject(arraysString[index]));
index ++; //遍历该记录的下一个字段
}
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {//关闭资源
if(resultSet!=null)resultSet.close();
if(statement!=null)statement.close();
if(connection!=null)connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}