JDBC simple code


1 .. write simple sql statement execution

DROP TABLE IF EXISTS `jdbctest`;
CREATE TABLE `jdbctest` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;

-- ----------------------------
-- Records of jdbctest
-- ----------------------------
INSERT INTO `jdbctest` VALUES ('1', 'tom');
INSERT INTO `jdbctest` VALUES ('2', 'marry');
INSERT INTO `jdbctest` VALUES ('3', 'kill');

image

2. Write operation jdbc database code (remember introduced mysql-connector-java-5.1.7- bin package)

com.newbe.jdbc1 Package Penalty for; 
Import java.sql. * ;
 / * * 
 * @Auther: newbe 
 * @email: [email protected] 
 * @date: 2019/9/2 22:27 
 * @Description: personal handwriting jdbc 
 * / 
public class MyJDBC {
     // define a database connection four elements: a drive name, url, user name and password 
    Private driver static String = "com.mysql.jdbc.Driver"; 
    Private the Url static String = "JDBC: MySQL: // localhost : 3306 / Test "; 
    Private static String UserName = " the root "; 
    Private PassWord static String = " 1234567 ";
    public static void main (String [] args) { 
        the try { 
            // . 1 . jdbc driver loading 
            the Class.forName (Driver); 
            // 2 . database connection 
            Connection Connection = the DriverManager.getConnection (the Url, UserName, PassWord);
             // 3 . Get Object pretreatment 
            String sql = " SELECT  *  from JDBCTest"; 
            the PreparedStatement statement = Connection.prepareStatement (sql);
             // . 4 . sql statement executed 
            the ResultSet Result =statement.executeQuery();
            //5.获取结果集取数据
            System.out.println("id"+" "+"name");
            while (result.next()){
                int id=result.getInt("id");
                String name=result.getString("name");
                System.out.println(id+" "+name);
            }
            System.out.println();
            //6.关闭连接
            result.close();
            statement.close();
            connection.close();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
        }
    }
}

3. Run results

image

Guess you like

Origin www.cnblogs.com/fby698/p/11450562.html