用JDBC连接MySQL数据库(包括查询,操作数据库)
具体步骤:
1.前期准备:要去网上下载一个连接mysql数据库的驱动的jar包,如果实maven的话可以直接去中央仓库查找一个mysql-connector-java的jar包,然后可以把上面的依赖代码拷贝到pom.xml中,然后右键项目MAVEN->update project,这时maven就会自动去中央仓库下载,并储存到本地仓库,不需要手动去下载然后放入lib文件这样。
2.加载驱动,用Class.forName("......")方法加载jar包中的驱动。
3.连接数据库,获得Connection类的对象。
4.通过Connection类的对象的方法获得Statement类的对象,接下来就可以用该类的对象操作数据库了。
代码如下:
package com;
import java.sql.*;
import java.util.logging.Logger;
import javax.naming.spi.DirStateFactory.Result;
public class DB
{
private Connection connection = null;
private ResultSet resultSet = null;
private Statement statement = null;
private String dbName = "db";
private String username = "root";
private String password = "admin";
private String url = "jdbc:mysql://localhost:3306/" + dbName;
private Logger logger = Logger.getLogger(this.getClass().getName());
public DB(){};
public Connection connect()
{
try
{
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
//此时MySQL的Driver已经加入到DriverManager中,然后连接数据库
connection = DriverManager.getConnection(url, username, password);
}
catch(Exception e)
{
logger.fine("连接失败");;
e.printStackTrace();
}
return connection;
}
//获得Statement类的对象,可以用此对象的方法执行sql语句
public Statement getStatement()
{
this.connect();
try
{
statement = connection.createStatement();
}catch (Exception e)
{
logger.info("获取statement失败");;
e.printStackTrace();
}
return statement;
}
//查询
public ResultSet search(String sql)
{
this.getStatement();
try
{
resultSet = statement.executeQuery(sql);
}
catch (Exception e)
{
logger.info("获取结果集失败");
e.printStackTrace();
}
logger.info("res" + resultSet);
return resultSet;
}
//更新数据库
public int dosql(String sql)
{
int i = -1;
this.getStatement();
try
{
i = statement.executeUpdate(sql);
}
catch(Exception e)
{
logger.info("更新失败");
e.printStackTrace();
}
return i;
}
}