MySQL安装与idea的连接
--编辑my.ini配置文件内容(Mysql 8.0以上不需要,直接安装即可)
[mysql]
# 设置mysql客户端默认字符集
default-character-set=utf8
[mysqld]
#设置3306端口
port = 3306
# 设置mysql的安装目录
basedir=E:\MySQL5.7.13\mysql-5.7.13-winx64
# 设置mysql数据库的数据的存放目录
datadir=E:\MySQL5.7.13\mysql-5.7.13-winx64\data
# 允许最大连接数
max_connections=200
# 服务端使用的字符集默认为8比特编码的latin1字符集
character-set-server=utf8
# 创建新表时将使用的默认存储引擎
default-storage-engine=INNODB
# 安装好后, 免密码进入mysql
skip-grant-tables
--用管理员身份运行cmd,输入命令
//安装mysql
mysqld -install
//安装成功后,初始化数据文件
mysqld --initialize-insecure --user=mysql
//进入mysql管理界面
mysql -u root-p
//修改密码
update mysql.user set password=password(’新密码’) where user=’root’;
//mysql8修改密码
alter user 'root'@'localhost' identified by '密码'
Mysql与idea进行连接
1.导入数据库驱动
点击连接进行下载:(mysql驱动)
https://github.com/epochong/mysql-connector-java-8.0.16.git
下载后在idea目录下新建lib目录,将下载好的驱动移动到lib目录下,并右击点击添加为库,再次点击驱动文件,若能展开,则驱动安装成功。
连接过程若出现驱动问题,需要注意查看驱动是否添加为库,英文版(add as library),查看驱动版本的问题(下载驱动需要对应与数据库,例mysql下载mysql驱动,sql server下载的是sql server驱动,查看是否在同一包下,有时候不在同一包下会找不到驱动)。
2.连接数据库(最基本的连接方法)
package jdbc_excise;
import java.sql.*;
public class Jdbc {
public static void main(String[] args) throws SQLException {
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=utf8&useSSL=false";
//通用模板:jdbc:数据库名字://地址:端口/实际使用数据库名称?附加参数
String username = "root";
String password = "123456";
Connection connection = DriverManager.getConnection(url,username,password);
Statement statement = connection.createStatement();
//执行sql查询语句
String sql = "select * from student";
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()){
System.out.println("Sno="+resultSet.getObject("Sno"));
}
resultSet.close();
statement.close();
connection.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
**附狂神教程中安全连接解决办法 **
jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=utf8&useSSL=false
若mysql版本高于驱动版本,则需要将安全连接置为false;置为true会报错。
封装工具类连接数据库
编写配置文件
--新建配置文件:db.properties--
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=utf8&useSSL=false
username=root
password=123456
封装工具类
package connect_jdbc.utils;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class JdbcUtils {
private static String driver = null;;
private static String url =null;
private static String username = null;
private static String password = null;
static {
try{
//通过反射得到配置文件中的内容
InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties");
Properties properties=new Properties();
properties.load(in);
driver = properties.getProperty("driver");
url = properties.getProperty("url");
username = properties.getProperty("username");
password = properties.getProperty("password");
//加载一次驱动
Class.forName(driver);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//获取连接
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url,username,password);
}
//释放连接
public static void release(Connection conn, Statement st, ResultSet rs){
if(rs!=null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(st!=null){
try {
st.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
编写测试类执行sql语句
//执行executeUpdate语句,实现增删改
package connect_jdbc.utils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcTest {
public static void main(String[] args) throws SQLException {
Connection connection =null;
Statement st = null;
ResultSet rs =null;
try {
connection = JdbcUtils.getConnection();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
st = connection.createStatement();
String sql = "insert into student (sno, sname, ssex, sclass, stel, sgroup, spassword)" +
"values (19070,'某某某','男','1900111','15711111111',3,'123456')";
int i = st.executeUpdate(sql);//返回值为整型,表示有几行受影响
if(i>0){
System.out.println("插入成功!");
}
JdbcUtils.release(connection,st,rs);
}
}
执行select语句
//执行executeQuery语句,实现查找
package connect_jdbc.utils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcSelect {
public static void main(String[] args) {
Connection connection = null;
Statement st = null;
ResultSet res = null;
try {
connection = JdbcUtils.getConnection();
st = connection.createStatement();
String sqls = "select * from student";
res = st.executeQuery(sqls);//返回值为查找的结果集
while (res.next())//进行结果集的输出
{
System.out.println(res.getObject("sno")+" "+res.getObject("sname"));
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
JdbcUtils.release(connection,st,res);
}
}
sql注入的问题及解决
问题描述:在使用statement函数执行sql操作时,当输入sql语句为:’ ‘or’1=1’或者’ 'or’values>0’时则会发生恒等于从而绕过查询语句,会发生将结果集绕过密码查询出来,从而形成安全威胁。
解决办法
将原先的statement函数改用preparedStatement函数,避免了sql注入,查询效率更高。
示例:
package connect_jdbc.utils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JdbcTestSe {
public static void main(String[] args) {
Connection connection =null;
PreparedStatement statement = null;
ResultSet res = null;
try {
connection = JdbcUtils.getConnection();
//与statement的区别,要使用?占位符代替参数,进行一次预编译
String sql = "insert into student (sno, sname, ssex, sclass, stel, sgroup, spassword)" +
"values (?,?,?,?,?,?,?)";
//手动给每一个参数(?)赋值
statement=connection.prepareStatement(sql);
statement.setString(1,"1907040124");
statement.setString(2,"薛某军");
statement.setString(3,"男");
statement.setString(4,"19070111");
statement.setString(5,"15711111111");
statement.setString(6,"3");
statement.setString(7,"123456");
//执行
int i = statement.executeUpdate();
if(i>0)
{
System.out.println("插入成功!");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
JdbcUtils.release(connection,statement,res);
}
}
使用数据库数据源进行操作
DBCP数据源
配置文件
#连接设置
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=true
username=root
password=123456
#!-- 初始化连接 --
initialSize=10
#最大连接数量
maxActive=50
#!-- 最大空闲连接 --
maxIdle=20
#!-- 最小空闲连接 --
minIdle=5
#!-- 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒 --
maxWait=60000
#JDBC驱动建立连接时附带的连接属性属性的格式必须为这样:【属性名=property;】
#注意:user 与 password 两个属性会被明确地传递,因此这里不需要包含他们。
connectionProperties=useUnicode=true;characterEncoding=UTF8
#指定由连接池所创建的连接的自动提交(auto-commit)状态。
defaultAutoCommit=true
#driver default 指定由连接池所创建的连接的只读(read-only)状态。
#如果没有设置该值,则“setReadOnly”方法将不被调用。(某些驱动并不支持只读模式,如:Informix)
defaultReadOnly=
#driver default 指定由连接池所创建的连接的事务级别(TransactionIsolation)。
#可用值为下列之一:(详情可见javadoc。)NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE
defaultTransactionIsolation=READ_UNCOMMITTED
C3P0数据源
配置文件
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<default-config>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/student</property>// <!-- 数据库的名字换成自己的数据库名字-->
<property name="user">root</property>
<property name="password">123456</property>
<property name="acquiredIncrement5">5</property>
<property name="initialPoolSize10">10</property>
<property name="minPoolSize5">5</property>
<property name="maxPoolSize20">20</property>
</default-config>
<!-- This app is massive! -->
<named-config name="MySQL">
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/student</property>
<property name="user">root</property>
<property name="password">123456</property><!-- 用户名和密码改成自己的-->
<property name="acquiredIncrement5">5</property>
<property name="initialPoolSize10">10</property>
<property name="minPoolSize5">5</property>
<property name="maxPoolSize20">20</property>
</named-config>
</c3p0-config>
封装C3P0的工具类
package jdbc_excise;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcUtilsC3P0 {
private static DataSource dataSource=null;
static {
try {
//创建数据源 工厂模式--》创建
dataSource =new ComboPooledDataSource("MySQL");
}catch (Exception e){
e.printStackTrace();
}
}
public static Connection getconnection() throws SQLException {
return dataSource.getConnection();
}
public static void release(Connection conn, Statement st, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(st!=null){
try {
st.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
测试类执行sql语句
package jdbc_excise;
import connect_jdbc.utils.JdbcUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class TestC3p0 {
public static void main(String[] args) {
Connection connection =null;
PreparedStatement statement = null;
ResultSet res = null;
try {
connection = JdbcUtilsC3P0.getconnection();
String sql = "insert into student (sno, sname, ssex, sclass, stel, sgroup, spassword)" +
"values (?,?,?,?,?,?,?)";
statement=connection.prepareStatement(sql);
statement.setString(1,"1907040126");
statement.setString(2,"薛某军");
statement.setString(3,"男");
statement.setString(4,"19070144");
statement.setString(5,"15711111111");
statement.setString(6,"3");
statement.setString(7,"123456");
System.out.println("连接成功!");
int i = statement.executeUpdate();
if(i>0)
{
System.out.println("插入成功!");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
JdbcUtilsC3P0.release(connection,statement,res);
}
}