java原生JDBC拼接sql并insert数据库

package JDBC;

import sun.jvm.hotspot.HelloWorld;

import java.io.*;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;

public class JDBCClass {
    public static void main(String[] args) {
        try{
            Class.forName("com.mysql.jdbc.Driver");
            System.out.println("驱动程序加载成功。。。");
        }catch (ClassNotFoundException e){
            e.printStackTrace();
            System.out.println("驱动程序加载失败。。。");
            //退出
            return;
        }
        Properties info = new Properties();
        try{
            String root = System.getProperty("user.dir");
            String FileName="jdbcConfig.properties";
            String filePath = root+ File.separator+"src/JDBC"+File.separator+FileName;
            BufferedReader input = new BufferedReader(new FileReader(filePath));
            info.load(input);
        }catch (IOException e){
            e.printStackTrace();
            return;
        }
        String url = (String) info.get("url");
        try (Connection conn = DriverManager.getConnection(url,info)){
            PreparedStatement pstmt = conn.prepareStatement("insert into table_jdbc values(?,?,?,?)");
            pstmt.setInt(1,2);
            pstmt.setString(2,"sunhy");
            pstmt.setInt(3,23);
            pstmt.setString(4,"女");
            pstmt.executeUpdate();
            System.out.println("数据库连接成功。。。");
        }catch (SQLException e){
            e.printStackTrace();
        }
    }
}
/*
 Navicat MySQL Data Transfer

 Source Server         : localhost
 Source Server Type    : MySQL
 Source Server Version : 50728
 Source Host           : 127.0.0.1:3306
 Source Schema         : mydemo1

 Target Server Type    : MySQL
 Target Server Version : 50728
 File Encoding         : 65001

 Date: 22/08/2020 12:27:40
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for table_jdbc
-- ----------------------------
DROP TABLE IF EXISTS `table_jdbc`;
CREATE TABLE `table_jdbc` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `name` varchar(50) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `sex` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

SET FOREIGN_KEY_CHECKS = 1;

 


版权声明:本文为hanjiaqian原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。