您的位置:首页 > 编程语言 > Java开发

Java学习-12 JDBC 连接mysql

2018-11-02 22:18 197 查看

步骤一:引入jar包    MySQL官网下载

              后在eclipse中找到项目文件后右击后bulidpath最后添加到library,或者直接复制jar到文件中右击addtobulidpath

步骤二 : 通过Java反射加载jar包中的 driver.class  驱动

           (下面jar包均为8.0版本)   

[code]	Class.forName("com.mysql.cj.jdbc.Driver");// 加载具体的驱动类

  步骤三:与数据库建立连接

              a:定义连接参数,URL尤其需重视

[code]	private static final String URL = "jdbc:mysql://localhost:3306/imooc?characterEncoding=utf8&useSSL=true&serverTimezone=UTC&autoReconnect=true";

private static final String USERNAME = "root";
private static final String PWD = "123123";

 

             b:连接

[code]	connection = DriverManager.getConnection(URL, USERNAME, PWD);

stmt = connection.createStatement();

  步骤四:发送sql语句,sql

 

 

 

  步骤五 :操作MySQL

[code]  int count = stmt.executeUpdate(sql);

 

例子

[code]import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class sqlTest {
public static void main(String[] args) {
String driverName = "com.mysql.cj.jdbc.Driver";
String URL="jdbc:mysql://127.0.0.1:3306/imooc?characterEncoding=utf8&useSSL=true&serverTimezone=UTC";
final String USER = "root";
final String  PWD = "123123";
Statement stmt = null;
Connection conn = null;

try{
Class.forName(driverName);
conn = DriverManager.getConnection(URL,USER,PWD);
stmt = conn.createStatement();
String sql = "update student set STUNAME='lasdasds' where stuno=2";
int count = stmt.executeUpdate(sql);
System.out.println(count);
}catch(ClassNotFoundException e){
e.printStackTrace();
}catch(SQLException e){
e.printStackTrace();
}
finally{
try{
stmt.close();
conn.close();

}catch(SQLException e){
e.printStackTrace();
}
}
}
}

 

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: