/**
* 添加学生的JDBC
* @author T283
*
*/
public class AddStu_JDBC {
public static void main(String[] args) throws Exception {
//1、注册驱动类
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
//2、连接数据库:字符串写错 会报错-对象无效
Connection con = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;DatabaseName=T283", "sa", "123");
System.out.println(con);
//3、创建Statement对象(用来执行sql语句)
Scanner sc = new Scanner(System.in);
System.out.println("请输入用户名:");
String name = sc.next();
System.out.println("请输入性别:");
String sex = sc.next();
System.out.println("请输入年龄:");
int age = sc.nextInt();
System.out.println("请输入爱好:");
String like = sc.next();
System.out.println("请输入地址:");
String address = sc.next();
System.out.println("请输入个性签名:");
String gxqm = sc.next();
// PreparedStatement ps = con.prepareStatement("insert into Student values('"+name+"','"+sex+"',"+age+",'"+like+"','"+address+"','"+gxqm+"')");
//占位符:?
String sql = "insert into Student values(?,?,?,?,?,?)";
PreparedStatement ps = con.prepareStatement(sql);
//4、给占位符赋值
ps.setString(1, name);//给第一个占位符赋值(姓名)
ps.setString(2, sex);//给第二个占位符赋值(性别)
ps.setInt(3, age);//给第3个占位符赋值(年龄)
ps.setString(4, like);//给第4个占位符赋值(爱好)
ps.setString(6, gxqm);//给第6个占位符赋值(个性签名)
ps.setString(5, address);//给第5个占位符赋值(地址)
//5、执行sql语句:增删改,返回受影响行数
int i = ps.executeUpdate();//接收受影响行数
System.out.println("受影响行数:"+i);
//6、处理结果(增删改返回受影响行数/查询返回查询的结果集)
if(i>0) {
System.out.println("添加成功");
}else {
System.out.println("添加失败");
}
//7、关闭连接(释放资源)
con.close();
ps.close();