java连接数据库

前言:1.数组不能扩容

           2.集合,数据保存在内存里,不能永久保存

           3.数据库可以把数据存放在硬盘里

            所以有了

           JAVA与数据库连接(工具exlipse,navicat)jdbc

          数据库:mysql,oracle,sqlserver,gbase,学习sql通用语句

          localhost和127.0.0.1表示本机ip

          mysql端口3306

           jdbc(java database connection)需要在exlipse导第三方包mysql-connector-java-5.1.47.jar

          在navicat里建booksys数据库,建book_table表,(book_id,book_name,book_author,book_price)

         book_id设为主键

          开始jdbc

        // 配置四大参数,获得连接1.用户名2.密码3.url 4.驱动
        // 加载驱动
          Class.forName("com.mysql.jdbc.Driver");
         // 填写url,用户名,密码获得连接
          Connection connection=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/booksys

            ?useUnicode=true&characterEncoding=utf-8","root","root123");

           System.out.println(connection);

           /如果连接成功控制台输出com.mysql.jdbc.JDBC4Connection@3d646c37

          /jdbc中文乱码问题,检查Java和数据库是不是utf_8格式,在jdbc:mysql://127.0.0.1:3306/booksys

           后面加?useUnicode=true&characterEncoding=utf-8

  
  

package book;

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

public class Test2 {

    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        
//        配置四大参数,获得连接1.用户名2.密码3.url  4.驱动
        
//        加载驱动
        Class.forName("com.mysql.jdbc.Driver");
//        填写url,用户名,密码获得连接
        Connection connection=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/booksys?useUnicode=true&characterEncoding=utf-8","root","root123");
        
        System.out.println(connection);
        
        
            /*    插入
             * 构造sql语句
             * 获得执行sql的对象(根据connection获得的)
             * 往sql里赋值
             * 执行
                */
//        String sql="insert into book_table(book_name,book_author) values(?,?)";
//        PreparedStatement statement=(PreparedStatement)connection.prepareStatement(sql);
//        statement.setString(1, "安徒生童话");
//        statement.setString(2, "安徒生");
//        int result=statement.executeUpdate();
//        System.out.println(result);
        
//        删除
        
//        String sql="delete from book_table where book_id=?";
//        PreparedStatement statement=(PreparedStatement)connection.prepareStatement(sql);
//        statement.setInt(1, 1);
//        int result=statement.executeUpdate();
//        System.out.println(result);
        
        
//        修改
        String sql="update book_table set book_price=? where book_id=?";
        PreparedStatement statement=(PreparedStatement)connection.prepareStatement(sql);
        statement.setInt(1, 66);
        statement.setInt(2, 2);
        int result=statement.executeUpdate();
         System.out.println(result);
        
        
        
    }

}

 


 

           

posted @ 2021-07-16 17:09  静静奇女子  阅读(169)  评论(0)    收藏  举报