本文主要是介绍JDBC连接数据库 prepareStatement,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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();
}}
这篇关于JDBC连接数据库 prepareStatement的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!