JDBC,数据库的连接

   1.建完工程后,右击工程,new,新建一个文件夹Folder,装jar包,
        2.将下载好的驱动包打开,找到jar文件,CTRL+C,选中装jar包的文件夹,CTRL+V,
        3.选中添加的jar,右键,Build Path,Add to Build Path
        4.新建一个包,再新建一个自定义类
        5.注册驱动:Class.forName("com.mysql.jdbc.Driver");throws异常
        6.获得链接,
          数据库的url:jdbc:mysql://localhost:3306/数据库名    
             //解决中文乱码:在url中数据库名后加?useUnicode=true&characterEncoding=utf8&autoReconnect=true&rewriteBatchedStatements=TRUE        
           Connection con = DriverManager.getConnection("");
          导包,java.sql,throws异常
             
        7.获得语句执行平台
                    通过连接对象获取对SQL语句的执行者对象
                    Statement stm=链接对象.createStatement();
        8.执行sql语句
                    使用执行者对象,向数据库执行SQL语句
                    获取到数据库的执行后的结果
                    
例子:

         

package com.oricle.Demo01;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class Demo01 {

    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        /*        1.建完工程后,右击工程,new,新建一个文件夹Folder,装jar包,
         *         2.将下载好的驱动包打开,找到jar文件,CTRL+C,选中装jar包的文件夹,CTRL+V,
         *         3.选中添加的jar,右键,Build Path,Add to Build Path 
         *         4.新建一个包,再新建一个自定义类
         *         5.注册驱动:Class.forName("com.mysql.jdbc.Driver");throws异常
         *         6.获得链接,
             *         数据库的url:jdbc:mysql://localhost:3306/数据库名    
             *         //解决中文乱码:在url中数据库名后加?useUnicode=true&characterEncoding=utf8&autoReconnect=true&rewriteBatchedStatements=TRUE        
         *             Connection con = DriverManager.getConnection("");
         *             导包,java.sql,throws异常
         *             
                7.获得语句执行平台
                    通过连接对象获取对SQL语句的执行者对象
                    Statement stm=链接对象.createStatement();
                8.执行sql语句
                    使用执行者对象,向数据库执行SQL语句
                    获取到数据库的执行后的结果
                    
         *         
        */
            //1注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            //2获得链接
            String url="jdbc:mysql://localhost:3306/fuxi?useUnicode=true&characterEncoding=utf8&autoReconnect=true&rewriteBatchedStatements=TRUE";
            String user="root";
            String password="123456";
            Connection con=DriverManager.getConnection(url, user, password);
            //3获得语句执行平台
            Statement stm=con.createStatement();
            //4.执行语句
            String sql="delete from sort where sid=5";
            stm.execute(sql);//增删改
            //5.针对于查询操作
            //6,先开的后关
            stm.close();
            con.close();
            
            
    }

}

猜你喜欢

转载自www.cnblogs.com/lzw123-/p/9436011.html