采用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+"条录被添加到数据表中");
}
}