本文讲述索引和事务,以及JDBC。 是关于MySQL的最后一弹啦~~ 重点小知识:MySQL数据库的存储结构是B+树!!
为了加快查询速度,数据库引入了索引 index
primary key / unique / foreign key 会自动创建索引
show index from 表名;create index 索引名 on 表名(列名);drop index 索引名 on 表名;注意事项:
根据事务的特点可知,使用事务执行SQL,开销更大,效率更低。
事务四大特性:原子性、一致性、持久性、隔离性。
start transaction; -- 开启事务
-- 执行多条sql
rollback/commit; -- 回滚或提交并发是指服务器同时处理多个客户端的请求。
并发处理事务,可能遇到的问题以及解决办法:

对于JDBC,数据库的插入、删除、修改的操作是类似的(数据库的插入、删除、修改操作,本文只讲解插入操作),但是查询操作是不一样的。

代码:
import com.mysql.cj.jdbc.MysqlDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class JDBCinsert {
public static void main(String[] args) throws SQLException {
//1.创建并初始化一个数据源
DataSource dataSource = new MysqlDataSource();
((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/suxi?characterEncoding=utf8&useSSL=false");
((MysqlDataSource)dataSource).setUser("root");
((MysqlDataSource)dataSource).setPassword("666666");
//2.和数据库服务器建立连接
Connection connection = dataSource.getConnection();
//3.构造sql语句
String sql = "insert into stu values(1,'李四')";
PreparedStatement statement = connection.prepareStatement(sql);
//4.执行sql语句
int ret = statement.executeUpdate();
System.out.println("ret="+ret);
//5.释放必要的资源
statement.close();
connection.close();
}
}对于代码中第三条构造sql,也可以替换成:
String sql = "insert into stu values(?,?)";// ? 是占位符
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1,id);
statement.setString(2,name);对于代码中第四条执行sql,插入,删除,修改使用的方法都是executeUpdate(),查找则是executeQuery().
和插入操作比较,查询操作不同的地方在于sql语句和第四点执行sql语句,以及第五点释放必要的资源,故这里只讲解不同的地方

代码:
//1.创建数据源
DataSource dataSource = new MysqlDataSource();
((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/suxi?characterEncoding=utf8&useSSL=false");
((MysqlDataSource)dataSource).setUser("root");
((MysqlDataSource)dataSource).setPassword("666666");
//2.连接服务器
Connection connection = dataSource.getConnection();
//3.构造sql
String sql = "select *from stu";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
//4.执行sql
ResultSet resultSet = preparedStatement.executeQuery();
while(resultSet.next()){
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
System.out.println("id="+id+"name="+name);
}
//5.释放资源
resultSet.close();
preparedStatement.close();
connection.close();关于MySQL,博主更文就到这里啦,我们下次再见~
这篇博客如果对你有帮助,给博主一个免费的点赞以示鼓励,欢迎各位🔎点赞👍评论收藏⭐,谢谢!!!