Java——JDBC

 

JDBC: Java DataBase Connectivity provides a consistent way to access a variety of relational database DBMS.

  1. API JDBC : provide a variety of access interfaces

     ①JDBC API functions:

     i. to establish a connection to the database

     ii. sending SQL statements

     iii. processing result is returned

  • The DriverManager : Management jdbc driver
  • Connection : connection
  • The Statement (the PreparedStatement) : CRUD   
  • CallableStatement : calling database stored procedures / functions storage
  • ResultSet : return result sets

Note: ①PreparedStatement Statement is a subclass ( subclass generally more powerful than the parent, because not only inherits all the parent class, as well as their own methods ).

use? When to placeholders. Then the PreparedStatement SetXxx () method to assign.

②PreparedStatement & Statement compare

stmt: there is the risk of sql injection

E.g. Input: Username: arbitrary value '  or =. 1. 1 -

          Password: any value

pstmt: prevent sql injection

 

2.JDBC access the database steps:

 

		public static void main(String[] args) {
        //连接对象
		Connection conn = null;
		//查询对象
		PreparedStatement pstmt = null;
		//结果集对象
		ResultSet rs = null;
		try {
			//加载数据库驱动
			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            //SqlServer的连接字符串
			String url ="jdbc:sqlserver://127.0.0.1:1433;DatabaseName =WJYLTeachingWebsite";
			//与数据库建立连接
			conn = DriverManager.getConnection(url, "sa","ROOT");
		    String sql = "select * from t_stu where stuSex = ?";
			//获取statement
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, "女");
			//查询 输入
			rs = pstmt.executeQuery();
			while(rs.next()) {
				System.out.println(rs.getString("stuNum")+"--"+ rs.getString("stuRealname")+"--"+rs.getString("stuSex"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
            //打开顺序与关闭顺序相反。先打开的最后关闭
			if(rs!=null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			}
			if(pstmt!=null) {
			try {
				pstmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			}
			if(conn!=null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			}
		}
}

 

ResultSet default points to the first row 0

So to use the RS, a first pointer to the first row first, i.e. rs.next ()

next () action: a down pointer (cursor) is empty after 2 down determination. Non-null return ture empty return false

Usually with the ResultSet.next () to traverse the result set.

        With ResultSet.getXXX () to retrieve the data.

Guess you like

Origin blog.csdn.net/weixin_42153410/article/details/91967663