import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import team.JDBCTest;
public class DBCStudent {
// 定义数据库访问参数
String url = "jdbc:sqlserver://localhost:1433;DatabaseName=JDBCTest";
String user = "sa";
String password = "aaaaaa";
static String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
Connection conn;
PreparedStatement ps;
ResultSet rs;
String id="";
String name="";
int age=0;
String sex="";
// 1、加载驱动
static {
try {
Class.forName(driverName);
} catch (ClassNotFoundException e) {
System.out.println("驱动加载失败");
}
}
// 2、创建连接对象
public Connection getConnection() throws SQLException{
conn=DriverManager.getConnection(url,user,password);
return conn;
}
public void add(String id,String name,int age,String sex) throws ClassNotFoundException, SQLException {
// 定义sql语句
String sql="INSERT INTO STUDENTMANAGE(STUDENTID,STUDENTNAME,AGE,SEX) VALUES(?,?,?,?)";
// 3、创建语句对象
ps=getConnection().prepareStatement(sql);
ps.setString(1,id);
ps.setString(2,name);
ps.setInt(3,age);
ps.setString(4,sex);
ps.executeUpdate();
// 4、遍历结果集:此处插入记录不需要
// 5、关闭资源对象
ps.close();
getConnection().close();
}
/*public void update(String id,String name,int age,String sex) throws ClassNotFoundException, SQLException {
// 定义sql语句
String sql="UPDATE STUDENTMANAGE SET STUDENTNAME=?,AGE=?,SEX=? where STUDENTID=?";
// 3、创建语句对象
ps=getConnection().prepareStatement(sql);
ps.setString(1,name);
ps.setInt(2,age);
ps.setString(3,sex);
ps.setString(4,id);
ps.executeUpdate();
// 4、遍历结果集:此处插入记录不需要
// 5、关闭资源对象
ps.close();
getConnection().close();
}
public void delete(String id) throws ClassNotFoundException, SQLException {
// 定义sql语句
String sql="DELETE STUDENTMANAGE WHERE STUDENTID=?";
// 3、创建语句对象
ps=getConnection().prepareStatement(sql);
ps.setString(1,id);
// 4、遍历结果集:此处插入记录不需要
// 5、关闭资源对象
ps.close();
getConnection().close();
}*/
public String get(String id) throws ClassNotFoundException, SQLException {
// 定义sql语句
String sql="SELECT STUDENTID,STUDENTNAME,AGE,SEX FROM STUDENTMANAGE WHERE STUDENTID=?";
// 3、创建语句对象
ps=getConnection().prepareStatement(sql);
ps.setString(1,id);
ResultSet rs = ps.executeQuery();
while(rs.next()){
id=rs.getString("STUDENTID");
name=rs.getString("STUDENTNAME");
age=rs.getInt("AGE");
sex=rs.getString("SEX");
}
// 4、遍历结果集:此处插入记录不需要
// 5、关闭资源对象
ps.close();
getConnection().close();
return "学号:"+id+" 姓名:"+name+" 年龄 :"+age+" 性别:"+sex;
}
public void get() throws ClassNotFoundException, SQLException {
}
public static void main(String[] args) throws ClassNotFoundException,SQLException {
//JDBCTest jt=new JDBCTest();
//jt.add();
//jt.update();
//jt.delete();
}
}