龙空技术网

mysql-connector-java与MySQL 8.X建立连接Demo

小飛象 112

前言:

而今小伙伴们对“java连接mysql课设”大体比较重视,兄弟们都需要了解一些“java连接mysql课设”的相关内容。那么小编同时在网上收集了一些关于“java连接mysql课设””的相关资讯,希望我们能喜欢,小伙伴们快快来了解一下吧!

数据库:

创建数据库:

create database maven;

create table user(

sid int primary key auto_increment,

sname varchar(20) not null

);

pom 文件:

不知道本地数据库版本的可以执行SQL语句查询:select version() from dual;

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

<version>8.0.11</version>

</dependency>

dao接口:

package cn.lys.dao;

import cn.lys.domain.Person;

import java.sql.SQLException;

import java.util.List;

public interface Dao {

public List<Person> findAll() throws Exception;

}

daoimpl实现:

package cn.lys.dao.impl;

import cn.lys.dao.Dao;

import cn.lys.domain.Person;

import java.sql.*;

import java.util.ArrayList;

import java.util.List;

public class DaoImpl implements Dao {

public List<Person> findAll() throws Exception {

List<Person> list = new ArrayList<Person>();

Connection connection = null;

PreparedStatement preparedStatement = null;

ResultSet resultSet = null;

try{

Class.forName("com.mysql.cj.jdbc.Driver");

//时区:东八区

connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/maven?serverTimezone=GMT%2B8&useSSL=false","root","root");

preparedStatement = connection.prepareStatement("select * from user");

resultSet = preparedStatement.executeQuery();

//把结果集转换为list集合

while (resultSet.next()){

Person person = new Person();

person.setId(resultSet.getInt("sid"));

person.setUsername(resultSet.getString("sname"));

list.add(person);

}

}catch (Exception e){

e.printStackTrace();

}finally {

resultSet.close();

preparedStatement.close();

connection.close();

}

return list;

}

}

test文件:

package cn.lys.test;

import cn.lys.dao.Dao;

import cn.lys.dao.impl.DaoImpl;

import cn.lys.domain.Person;

import org.junit.Test;

import java.util.List;

public class test {

@Test

public void findAllTest(){

Dao dao = new DaoImpl();

try {

List<Person> list = dao.findAll();

for (Person person : list) {

System.out.println(person.getId());

System.out.println(person.getUsername());

}

} catch (Exception e) {

e.printStackTrace();

}

}

}

标签: #java连接mysql课设