Java代码操控Mysql数据库
import com.mysql.cj.jdbc.MysqlDataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Mysql {
public static void main(String[] args) throws SQLException {
//创建数据源对象
MysqlDataSource mysqlDataSource = new MysqlDataSource();
//指定数据源参数
mysqlDataSource.setUser("root");
mysqlDataSource.setPassword("");
mysqlDataSource.setURL("jdbc:mysql://localhost:3306/l?characterEncoding=utf8&useSSL=true");
String sql = "select * from 学生;";
try {
//连接数据库
Connection connection = mysqlDataSource.getConnection();
//操控数据库
PreparedStatement preparedStatement = connection.prepareStatement(sql);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
System.out.println(resultSet.getInt("姓名"));
}
//操控
resultSet.close();
preparedStatement.close();
connection.close();
} catch (Exception exception) {
System.out.println(exception.toString());
}
}
}
下面是上面代码详解
1.创建数据源对象
需要导入包
import com.mysql.cj.jdbc.MysqlDataSource;
创建数据源对象
MysqlDataSource mysqlDataSource = new MysqlDataSource();
2.指定数据源参数
mysqlDataSource.setUser("root");
mysqlDataSource.setPassword("");
mysqlDataSource.setURL("jdbc:mysql://localhost:3306/l?useSSL=true&serverTimezone=UTC");
"jdbc:mysql://localhost:3306/l?useSSL=true&serverTimezone=UTC"
"jdbc:mysql://localhost:3306/l?characterEncoding=utf8&useSSL=true"
characterEncoding=utf8 用来设置字符集
3.与服务器建立连接
需要导入包
import java.sql.Connection;
建立连接
Connection connection = mysqlDataSource.getConnection();
可能会抛出异常,需要在方法头部加入
throws SQLException
或者放入try-catch
块中
4.操控数据库
(1).结构或数据操作语句
creat、drop、delete、insert、update…
例如创建数据表
sql语句直接写到字符串中
String sql = "create table 学生 (姓名 int);";
执行语句
PreparedStatement preparedStatement = connection.prepareStatement(sql);
int ref = preparedStatement.executeUpdate();
变量ref为int类型,表示影响的数据行
(2).查询操作语句
String sql = "select * from 学生;";
执行语句
PreparedStatement preparedStatement = connection.prepareStatement(sql);
ResultSet resultSet = preparedStatement.executeQuery();
ResultSet是结果集,因为查询操作的结果是个集合
查看结果集中的数据
while (resultSet.next()) {
int name = resultSet.getInt("姓名")
System.out.println(name);
}
resultSet.next()
这句用来判断结果集中的下一条记录是不是空
resultSet.getInt("姓名")
这句用来获取列名为姓名的记录的值
可以扩展为
resultSet.getXXX("列名")
XXX可以是Int、Double、Date等
关闭
resultSet.close();
preparedStatement.close();
connection.close();
如果没有resultSet,那么直接关闭后面的
preparedStatement.close();
connection.close();
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/122858.html