赞
踩
在eclipse添加数据库数据代码:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Scanner;
/**
* 添加学生的JDBC
* @author boo
*
*/
public class Add_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 = school", "sa", "123");
System.out.println(con);
//3、创建Statement对象(用来执行sql语句)
Scanner sc = new Scanner(System.in);
System.out.println("请输入用户名:");
String sname = sc.next();
System.out.println("请输入性别:");
String ssex = sc.next();
System.out.println("请输入年龄:");
int sgae = sc.nextInt();
System.out.println("请输入地址:");
String saddress = sc.next();
System.out.println("请输入个性签名:");
String sinfo = sc.next();
// PreparedStatement ps = con.prepareStatement("insert into boo values('"+sname+"','"+ssex+"','"+sgae+"','"+saddress+"','"+sinfo+"')");
//占位符:?
String sql = "insert into boo values(?,?,?,?,?)";
PreparedStatement ps = con.prepareStatement(sql);
//4、给占位符赋值
ps.setString(1, sname);
ps.setString(2, ssex);
ps.setInt(3, sgae);
ps.setString(4, saddress);
ps.setString(5, sinfo);
//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();
}
}
查询代码:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
/**
* 查询所有学生
* @author d
*
*/
public class Select_JDBC {
public static void main(String[] args) throws Exception {
//1、注册驱动类
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
//2、连接数据库
String url = "jdbc:sqlserver://localhost:1433;DatabaseName=school";
Connection con = DriverManager.getConnection(url,"sa","123");
//3、创建PreparedStatement对象,用来执行sql语句
String sql = "select * from boo";
PreparedStatement ps = con.prepareStatement(sql);
//4、给占位符赋值
//5、执行sql语句(接收结果集)
ResultSet rs = ps.executeQuery();
//6、处理结果:遍历结果集
while(rs.next()) {
int sid = rs.getInt(1);
String sname = rs.getString(2);
String ssex = rs.getString(3);
int sgae = rs.getInt(4);
String saddress = rs.getString(5);
String sinfo = rs.getString(6);
System.out.println("学号:"+sid+"\t姓名:"+sname+"\t\t性别:"+ssex+"\t\t年龄:"+sgae+"\t\t地址:"+saddress+"\t\t个性签名:"+sinfo);
}
//7、关闭连接
rs.close();
con.close();
ps.close();
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。