附上代码和结果:importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.ResultSet;importjava.sql.SQLException;importjava.sql.Statement;publicclassInsertData...
附上代码和结果:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class InsertData {
static Connection con;
public static Connection getConnection() { //建立返回值为Connection的方法
try {
Class.forName("com.mysql.jdbc.Driver"); //加载数据库驱动
System.out.println("数据库驱动加载成功");
con = DriverManager
.getConnection(
"jdbc:mysql://localhost:3306/db_test1",
"root", ""); // 获取数据库连接
if (con != null) {
System.out.println("数据库连接成功");
}
} catch (Exception e) {
e.printStackTrace();
}
return con; //按方法要求返回个Connection对象
}
/**
* @param args
*/
public static void main(String[] args) {
con = getConnection(); // 调用数据库连接方法
Statement statement;
try {
statement = con.createStatement(); // 获取Statement对象
for(int i=0;i<3;i++){
statement.execute("insert into tb_student(name,sex,age,salary)values('小红','女',24,5000)"); // 执行添加数据操作
}
System.out.println("student表的所有记录:");
ResultSet res=statement.executeQuery("select * from tb_student"); //查询所有记录
while(res.next()){
int id=res.getInt("id");
String name=res.getString("name");
String sex=res.getString("sex");
int age=res.getInt("age");
int salary=res.getInt("salary");
System.out.println("id:"+id+"\t姓名:"+name+"\t性别:"+sex+"\t\t年龄:"+age+"\t\t工资:"+salary);
}
//关闭连接
res.close();
statement.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
展开