注册驱动
Class.forName("com.mysql.jdbc.Driver");
获取连接
String url = "jdbc:mysql://localhost:3306/myhqy2?characterEncoding=utf8&useSSL=false";
Connection conn = DriverManager.getConnection(url, "root", "123456");
url:连接字符串 jdbc:mysql://localhost:3306(连接的地址)/要连接的数据库名称
user:mysql用户名
password:mysql密码
characterEncoding=utf8设置编码集表示使用的编码是utf8
useSSL=false 不使用SSL安全,安全连接需要证书
创建命令对象
Statement stat = conn.createStatement();
执行命令
返回的是受影响的行数
excute:可以执行任何的sql语句
excuteUpdate():可以执行DML insert、update、dalete,DDL create database、create table
int i = stat.executeUpdate("create database myhqy2");//创建名为myhqy2的数据库
System.out.println("结果:"+i);
关闭
命令和连接都要关闭
stat.close();
conn.close();
System.out.println("执行完毕");
完整代码
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class JBDCDemo01 {
public static void main(String[] args) throws Exception {
//注册驱动
Class.forName("com.mysql.jdbc.Driver");
//获取连接
/*
url 连接字符串 jdbc:mysql://localhost:3306(连接的地址)/要连接的数据库名称
user 用户名
password 密码
characterEncoding=utf8设置编码集表示使用的编码utf8
useSSL=false 不使用SSL安全,安全连接需要证书
*/
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb1?characterEncoding=utf8&useSSL=false", "root", "123456");
if(conn != null){
System.out.println("连接成功!");
}
//创建命令对象在这里插入代码片
Statement stat = conn.createStatement();
//执行命令
//返回值是受影响的行数
/*
execute():可以执行任何的sql语句
executeUpdate():可以执行DML insert update dalete ,DDL create database、create table
*/
int i = stat.executeUpdate("create database myhqy2");//创建名为myhqy2的数据库
System.out.println("结果:"+i);
//关闭 命令和连接都要关闭
stat.close();
conn.close();
System.out.println("执行完毕");
}
}