JDBC(3)

注册驱动

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("执行完毕");


            }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值