mysql-connector-java-5.1.44-bin.jar的链接:
https://pan.baidu.com/s/1VfsXgJqxGSetGpror-agIA
package link;
import java.sql.*;
import java.util.*;
public class insert {
public static void main(String args[]) {
//连接数据源
//声明Connection对象
Connection con=null;
//驱动程序名
String driver ="com.mysql.jdbc.Driver";
//URL指向要访问的数据库名mydata
String url = "jdbc:mysql://xxxxxxx:3306/表的名字?user=用户名&password=密码&useUnicode=true&characterEncoding=UTF8&useSSL=true";
//MySQL配置时的用户名和密码
//String user = "xxx";
//String password = "xxx";
//便利查询结果集
try {
//加载驱动程序:通过java.lang.Class类的静态方法forName(String className)实现,加载想要连接的数据库的驱动到JVM(Java虚拟机)
//成功加载后,会将Driver类的实例注册到DriverManager类中
Class.forName(driver);
//1.getConnection()方法,连接MySQL数据库
//连接URL定义了连接数据库时的协议、子协议、数据源标识,书写形式:协议:子协议:数据源标识
con=DriverManager.getConnection(url); //user,password
if(!con.isClosed()) System.out.println("Succeeded connecting to the Database!");
//2.创建statement类对象,用来执行SQL语句
Statement statement = con.createStatement();
//System.out.println("-------------");
//System.out.println("姓名");
//插入名字
String sql="insert into 表的名字(表的表头) values('...插入的东西')";
statement.executeUpdate(sql);//执行sql语句
System.out.println("插入到数据库成功");
//删除名字
//String sql="delete from t_first_table where name='...'";
//statement.executeUpdate(sql);
//3.ResultSet类,用来存放获取的结果集
String name=null;
ResultSet rs = statement.executeQuery("SELECT * FROM 表的名字");
while(rs.next()) {
//获取数据
name=rs.getString("name");
System.out.println(name);
}
rs.close();
con.close();
}
catch(ClassNotFoundException e) {
//数据库驱动类异常处理:找不到驱动程序类 ,加载驱动失败
System.out.println("Sorry,can`t find the Driver!");
e.printStackTrace();
}
catch(SQLException e) {
//数据库连接失败异常处理
e.printStackTrace();
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
finally{
System.out.println("数据库数据成功获取!!");
}
}
}