向数据库添加数据

采用Statment实例静态向数据表中添加一条记录:

package com.myjdbc;
import java.security.PublicKey;
import	java.sql.Connection;
import  java.sql.SQLException;
import  java.sql.PreparedStatement;
import  java.sql.Statement;


public class InserRecord {
	DBConnection	oneCon = new DBConnection();
	Connection		con = null;
	private Statement stmt  = null;
	private PreparedStatement pstmt = null;
	
	public InserRecord() {
		// TODO Auto-generated constructor stub
	}
	
	public boolean addStudentDataInfo()
	{
		con = oneCon.getConnection();
		boolean returnResult = true;
		
		try {
			stmt = con.createStatement();
			
			String r1 = "insert into student(sno, sname, sage, smajor) values('20190810', 'zeng', 28, 'cs')";
			stmt.executeUpdate(r1);
			stmt.close();
			con.close();
		} catch (SQLException e) {
			// TODO: handle exception
			System.out.println("数据库读异常");
			e.printStackTrace();
			returnResult = false;
		}
		return returnResult;
	}
	
	public int addStudentDataInfo(String sno, String sname, int sage, String smajor) {
		int count = 0;
		
		con = oneCon.getConnection();
		try {
			String string = "insert into student values(?,?,?,?)";
			pstmt = con.prepareStatement(string);
			pstmt.setString(1, sno);
			pstmt.setString(2, sname);
			pstmt.setInt(3, sage);
			pstmt.setString(4, smajor);
			count = pstmt.executeUpdate();
		} catch (SQLException e) {
			// TODO: handle exception
			e.printStackTrace();
		}finally{
			try{
				pstmt.close();
				con.close();
			}catch(SQLException e){
				e.printStackTrace();
				System.out.println("关闭数据库异常");				
			}			
		}
		return count;
	}

	
	public static void main(String[] args){
		InserRecord c = new InserRecord();
		boolean isSuccess = c.addStudentDataInfo();
		if (isSuccess)
			System.out.println("The data is added.");
		else
			System.out.println("The data is not added.");
		int count = c.addStudentDataInfo("20190810", "zhangshan", 20, "123");
		System.out.println(count+"条录被添加到数据表中");
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值