package First;
import com.mysql.jdbc.Driver;
import org.junit.Test;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
方式一是静态加载依赖性比较强不推荐使用
public class JDBC_01 {
public static void main(String[] args) throws SQLException {
//方式1:静态加载
@Test
public void method_01() throws SQLException {
//前置工作:在项目下创建文件夹,将mysql jar文件拷贝过来在add as Library 后加入项目中
//1,注册驱动
Driver driver = new Driver();//创建driver对象
//2,得到连接
String url = "jdbc:mysql://localhost:3306/firsttry?useSSL=false";
Properties properties = new Properties();
properties.setProperty("user","root");//用户
properties.setProperty("password","zty");//密码
//获取连接
Connection connect = driver.connect(url, properties);
//3,执行sql
String sql = "insert into onetable values('10','JDBCsql','2000')";
Statement statement = connect.createStatement();//用于执行静态sql语句并返回生成的结果的对象
int rows = statement.executeUpdate(sql);//如果是dml语句,返回的就是影响的行数
System.out.println(rows);
//4,关闭连接资源
statement.close();
connect.close();
}
方式二是动态加载依赖性不强,可以单独写到properties文件里,方便开发者修改,推荐使用
//方式2:动态加载
@Test
public void method_02() throws ClassNotFoundException, IllegalAccessException, InstantiationException, SQLException {
//注册驱动
Class aClass = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver)aClass.newInstance();
//获取连接
String url ="jdbc:mysql://localhost:3306/firsttry?useSSL=false";
Properties properties = new Properties();
properties.setProperty("user","root");
properties.setProperty("password","zty");
Connection connect = driver.connect(url, properties);
//执行Mysql
String sql = "insert into onetable values('20','JDBCsql','2000')";
Statement statement = connect.createStatement();//用于执行静态sql语句并返回生成的结果的对象
int rows = statement.executeUpdate(sql);//如果是dml语句,返回的就是影响的行数
System.out.println(rows);
//4,关闭连接资源
statement.close();
connect.close();
}
}



