JDBC:灵活指定SQL中的变量(SXT)
Demo
- import java.sql.*;
- import com.sun.org.apache.xalan.internal.xsltc.runtime.Parameter;
- public class TestPrepState
- {
- /**
- * PreparedStatement的简单使用
- * 灵活指定SQL中的变量
- * 手动输入参数
- */
- public static void main(String[] args)
- {
- // TODO Auto-generated method stub
- if (args.length != 4)
- {
- System.out.println("Error,plesase input again!");
- System.exit(-1);
- }
- int userid = 0;
- try
- {
- userid = Integer.parseInt(args[0]);
- } catch (NumberFormatException e)
- {
- System.out.println("Number error");
- System.exit(-1);
- }
- String usernameString = args[1];
- String passwordString = args[2];
- String userflaString = args[3];
- Connection conn = null;
- PreparedStatement pstmt = null;
- //引用包的时候注意:这个PreparedStatement是java.sql中的,而不是com.mysql.jdbc中的那个PreparedStatement
- ResultSet rs = null;
- try
- {
- Class.forName("com.mysql.jdbc.Driver");
- String url = "jdbc:mysql://localhost:3306/college";
- String user = "root";
- String password = "123456";
- conn = DriverManager.getConnection(url, user, password);
- pstmt = conn.prepareStatement("insert into user values(?,?,?,?)");
- pstmt.setInt(1, userid);
- pstmt.setString(2, usernameString);
- pstmt.setString(3, passwordString);
- pstmt.setString(4, userflaString);
- pstmt.executeUpdate();
- rs = pstmt.executeQuery("select * from user where userId='"+userid+"'");
- while (rs.next())
- {
- System.out.print("username:");
- System.out.println(rs.getString("userName"));
- System.out.print("password:");
- System.out.println(rs.getString("userPassword"));
- }
- } catch (ClassNotFoundException e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (SQLException e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } finally
- {
- try
- {
- if (rs != null)
- {
- rs.close();
- rs = null;
- }
- if (pstmt != null)
- {
- pstmt.close();
- pstmt.close();
- }
- if (conn != null)
- {
- conn.close();
- conn = null;
- }
- } catch (SQLException e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- }