1. 在工程目录中创建lib文件夹,将下载好的JDBC(MySQL连接驱动:mysql-connector-java-5.1.27.jar)放到该文件夹下。
2.导入该驱动
3.在数据库(javaText)中创建一个表Demo
4.添加数据
import java.sql.*;
public class DBUtil {
// JDBC 驱动名及数据库 URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/javatext";
// 数据库的用户名与密码,需要根据自己的设置
static final String USER = "root";
static final String PASS = "970821";
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
//连接数据库
public Connection getConnection() {
try {
Class.forName(JDBC_DRIVER);// 加载驱动,必须导入包mysql-connector-java-5.1.45-bin.jar
connection = DriverManager.getConnection(DB_URL,USER,PASS);//连接数据库
} catch (Exception e) {
e.printStackTrace();
}
return connection;
}
//关闭数据库
public void closeDB(){
try {
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//执行查询sql语句
public ResultSet selectSQL(String sql) {
try {
statement = connection.prepareStatement(sql);
resultSet = statement.executeQuery(sql);
} catch (Exception e) {
e.printStackTrace();
}
return resultSet;
}
//执行插入sql语句
public boolean insertSQL(String sql){
try {
statement = connection.prepareStatement(sql);
statement.executeUpdate();
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
//执行删除sql语句
public boolean deleteSQL(String sql){
try {
statement = connection.prepareStatement(sql);
statement.executeUpdate();
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
//执行代表sql语句
public boolean updateSQL(String sql){
try {
statement = connection.prepareStatement(sql);
statement.executeUpdate();
return true;
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
//打印结果集
public void show(ResultSet rs){
System.out.println("查询结果:");
try {
while (rs.next()) {
System.out.println(rs.getInt(1) + "/t/t" +
rs.getString(2) + "/t/t" +
rs.getString(3));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
//sql语句
//String select = "select * from users";
//String insert = "insert into users(userID,userName,userPWD) values('10000','10000','10000')";
//String update = "update users set userPWD =20000 where userID= '10000'";
//String delete = "delete from users where userID= '10000'";
public static void main(String[] args) {
DBUtil dao = new DBUtil();
dao.getConnection();
String select = "select * from Demo";
String insert = "insert into Demo(id,name,url,alexa,country) values('1','QQ','http://www.QQ.com','10000','CN')";
String update = "update Demo set name ='微信 ' where id= '2'";
String delete = "delete from Demo where id= '1'";
if (dao.insertSQL(insert) == true) {
ResultSet resultSet = dao.selectSQL(select);
dao.show(resultSet);
}
if (dao.updateSQL(update) == true) {
ResultSet resultSet = dao.selectSQL(select);
dao.show(resultSet);
}
if (dao.deleteSQL(delete) == true) {
ResultSet resultSet = dao.selectSQL(select);
dao.show(resultSet);
}
dao.closeDB();
}
}