会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 132358个问题

image.png

JAVA 全系列/第三阶段:数据库编程/JDBC技术 1951楼
JAVA 全系列/第三阶段:数据库编程/JDBC技术 1952楼

create table numbers
(
	id int auto_increment primary key,
	num int not null,
	type varchar(2)
);

我使用的是mySql,已经把id设置为自动增长

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;

/**
 *使用PreparedStatement批处理数据
 *将2~1000之间的数字插入数据库,并记录数字的类型(质数还是合数)
 *
 */
public class TestNum {
	
	public static void main(String[] args) throws Exception {
		int num=1000;
		long startTime=System.currentTimeMillis();
//		insertNum1(num);//	使用Statement插入数字
//		System.out.println("使用statement耗时:"+(endTime-startTime));
		
		insertNum2(num);//	使用PreparedStatement插入数字
		long endTime=System.currentTimeMillis();
		System.out.println("使用PreparedStatement耗时:"+(endTime-startTime));
	}
	/**
	 * 使用PreparedStatement插入数字,批处理
	 * @throws Exception 
	 */
	private static void insertNum2(int num) throws Exception {		
		Connection conn = JDBCUtils.getConnection();
		String sql="insert into numbers  values(null,?,?)";
		PreparedStatement state=conn.prepareStatement(sql);
		conn.setAutoCommit(false);//关闭自动提交
		for(int i=2;i<=num;i++) {
			//绑定参数
			JDBCUtils.bind(state,i,getType(i));
			//加入批处理
			state.addBatch();		
		}		
		//统一执行批处理
		state.executeBatch();
		conn.commit();
		JDBCUtils.relese(state, conn);
		
	}
	/**
	 * 使用Statement插入数字,并且只开关一次连接
	 * @throws Exception 
	 * 
	 */
	private static void insertNum1(int num) throws Exception {
		Connection conn=JDBCUtils.getConnection();
		Statement state=conn.createStatement();
		for(int i=2;i<=num;i++) {
			String sql="insert into numbers values(null,"+i+",'"+getType(i)+"')";
			state.executeUpdate(sql);
		}		
		JDBCUtils.relese(state, conn);
	}
	/**
	 * 判断数字类型
	 * @return
	 */
	private static String getType(int num) {
		if(num<4) {
			return "ZS";
		}
		for(int i=2;i<Math.sqrt(num);i++) {
			if(num % i==0) {
				return "HS";
			}
		}
		return "ZS";
	}
}

在测试PreparedStatement时,就只是需要绑定两个参数了,将id那个设置为null,运行时出现异常,这是为什么呢?

image.png

JAVA 全系列/第三阶段:数据库编程/JDBC技术(旧) 1953楼

数据已经添加,但是有报错,查不到报错原因:

运行报错

Mon Jul 15 12:54:15 CST 2019 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.

1

代码

package cn.bjsxt.jdbc;

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



public class JdbcTest {
	//向Departments表中添加一条数据
	public void insertDepartments(String department_name,int location_id ){
		//注册驱动
		Connection conn = null;
		Statement state = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			//创建连接
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjsxt?useUnicode=true&characterEncoding=utf-8","root","123456");
			String sql="insert into departments values(default,'"+department_name+"',"+location_id+")" ;
			state = conn.createStatement();
			int flag = state.executeUpdate(sql);
			System.out.println(flag);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(state!=null){
				try {
					state.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(conn!=null){
				try {
					conn.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	public static void main(String [] args){
		JdbcTest test = new JdbcTest();
		test.insertDepartments("研发部",8);
	}

}


JAVA 全系列/第三阶段:数据库编程/JDBC技术(旧) 1955楼
JAVA 全系列/第三阶段:数据库编程/MySQL数据库的使用 1958楼

问题在哪呀

package com.llz.jdbc;

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

public class JdbcUtil {
    private static String driver;
    private static String JdbcUrl;
    private static String userName;
    private static String userPassword ;
    static {
        ResourceBundle bundle = ResourceBundle.getBundle("Jdbc");
        driver = bundle.getString("driver");
        JdbcUrl = bundle.getString("JdbcUrl");
        userName = bundle.getString("userName");
        userPassword = bundle.getString("userPassword");
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    //获取connection对象
    public static Connection getConnection() {
        Connection conn = null;

        try {
            conn = DriverManager.getConnection(JdbcUrl, userName, userPassword);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return conn;
    }
    //关闭
    public static void closeState(Statement state){
        if(state!=null){
            try {
                state.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

    }
    public static void closeConn(Connection conn){
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

    }

}
package com.llz.jdbc;


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

class JdbcTest{
    public void test(int id,String address,int amount){
        Connection conn = null;
        Statement state = null;
        try{
            conn = JdbcUtil.getConnection();
            String sql = "insert into goodcount values('"+id+"','"+address+"','"+amount+"')";
            state = conn.createStatement();
            int flag = state.executeUpdate(sql);
            System.out.println(flag);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JdbcUtil.closeState(state);
            JdbcUtil.closeConn(conn);
        }
    }
    public void updateTest(int id,String address,int amount){
        Connection conn = null;
        Statement state = null;
        try{
            conn=JdbcUtil.getConnection();
            String sql = "update goodcount set id = '"+id+"',address='"+address+"' where amount="+amount+"";
            state = conn.createStatement();
            int flag = state.executeUpdate(sql);
            System.out.println(flag);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JdbcUtil.closeConn(conn);
            JdbcUtil.closeState(state);
        }
    }
}
public class StatementTest {
    public static void main(String[] args) {

        JdbcTest jt = new JdbcTest();
        jt.test(6,"重庆",5);
        //jt.updateTest(8,"湖南",5);
    }
}
driver = com.mysql.jdbc.Driver
JdbcUrl = jdbc:mysql://localhost:3306/good?useUnicode=true&characterEncoding=utf-8
userName = root
userPassword =123456


JAVA 全系列/第三阶段:数据库编程/JDBC技术(旧) 1959楼
JAVA 全系列/第三阶段:数据库编程/JDBC技术(旧) 1961楼
JAVA 全系列/第三阶段:数据库编程/JDBC技术 1964楼
JAVA 全系列/第三阶段:数据库编程/JDBC技术(旧) 1965楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

©2014-2025百战汇智(北京)科技有限公司 All Rights Reserved 北京亦庄经济开发区科创十四街 赛蒂国际工业园
网站维护:百战汇智(北京)科技有限公司
京公网安备 11011402011233号    京ICP备18060230号-3    营业执照    经营许可证:京B2-20212637