我正在使用servlet和数据库。我遇到了一个问题。我有一个用默认值填充数据库的sql脚本。
DROP TABLE roles;
DROP TABLE users;
CREATE table roles(
id int NOT NULL PRIMARY KEY,
name varchar(10) not null UNIQUE
);
insert into roles(id, name) values (0, 'admin');
insert into roles(id, name) values (1, 'client');
create table users(
id int not null AUTO_INCREMENT,
first_name varchar(20) not null,
last_name varchar(20) not null,
email varchar(30) not null unique,
password varchar(20) not null,
blocked boolean default false,
avatar varchar(20) not null,
role_id int not null references roles(id)
ON DELETE CASCADE
ON UPDATE RESTRICT
);
INSERT INTO users(id, first_name, last_name, email, password, blocked, avatar, role_id) VALUES(default, 'John', 'Smith', 'john.smith@gmail.com', '12345678Aa$', default, '2.png' 1);
INSERT INTO users(id, first_name, last_name, email, password, blocked, avatar, role_id) VALUES(default, 'George', 'Anderson', 'george_anderson123@mail.ru', '12345678Aa$', true, '3.png', 1);
之后,我尝试通过BasicDataSource与数据库建立连接:
public static BasicDataSource getPoolConnection() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/shop_db");
dataSource.setUsername("root");
dataSource.setPassword("root");
dataSource.setConnectionProperties("useSSL=false;");
return dataSource;
}
创建实例:
public void contextInitialized(ServletContextEvent event) {
BasicDataSource dataSource = ConnectionPool.getPoolConnection();
UserService userService = new service.impl.UserService(dataSource);
}
但是在尝试注册新用户后,我得到了一个空指针。我认为这是由于以下事实:当我尝试比较数据库中的电子邮件并输入字段时,我的数据库为空
@Override
public boolean isExist(String email) {
return transactionManager.doInTransaction(
connection ->
userDAO.isExist(email, connection)
);
}
TransactionManager:
public TransactionManager(DataSource dataSource) {
this.dataSource = dataSource;
}
public <T> T doInTransaction(TransactionOperation<T> operation) {
T result = null;
Connection connection = null;
try {
connection = dataSource.getConnection();
connection.setAutoCommit(false);
connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
result = operation.operation(connection);
connection.commit();
} catch (SQLException e) {
try {
if (connection != null) {
connection.rollback();
}
} catch (SQLException e1) {
e1.printStackTrace();
}
} finally {
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return result;
}
如何运行sql脚本以在社区版中执行?