- package com.hanchao.jdbc;
-
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
-
-
-
-
-
-
- public class TestJdbcNew {
-
-
-
-
-
-
-
-
-
-
-
-
- public static void main(String[] args) throws Exception {
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- retrieve(15);
- }
-
-
-
-
-
-
-
- public static void insert(String username,String address) throws Exception {
- Class.forName("com.mysql.jdbc.Driver");
- Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/mydb","root","root");
-
-
- String sql = "insert into t_user(username,address) values(?,?)";
- PreparedStatement sta = con.prepareStatement(sql);
- sta.setString(1, username);
- sta.setString(2, address);
-
- int rows = sta.executeUpdate();
- if(rows > 0) {
- System.out.println("operate successfully!");
- }
- sta.close();
- con.close();
- }
-
-
-
-
-
-
-
-
- public static void update(String address,int id) throws Exception {
- Class.forName("com.mysql.jdbc.Driver");
- Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/mydb","root","root");
-
-
- String sql = "update t_user set address=? where id=?";
- PreparedStatement sta = con.prepareStatement(sql);
- sta.setString(1, address);
- sta.setInt(2, id);
-
- int rows = sta.executeUpdate();
- if(rows > 0) {
- System.out.println("operate successfully");
- }
- sta.close();
- con.close();
-
- }
-
-
-
-
-
-
-
- public static void delete(int id) throws Exception {
- Class.forName("com.mysql.jdbc.Driver");
- Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/mydb","root","root");
-
-
- String sql = "delete from t_user where id=?";
- PreparedStatement sta = con.prepareStatement(sql);
- sta.setInt(1, id);
-
- int rows = sta.executeUpdate();
- if(rows > 0) {
- System.out.println("operate successfully!!");
- }
- sta.close();
- con.close();
- }
-
-
-
-
-
-
-
- public static void retrieve(int id) throws Exception {
- Class.forName("com.mysql.jdbc.Driver");
- Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/mydb","root","root");
-
-
- String sql = "select id,username,address from t_user where id=?";
- PreparedStatement sta = con.prepareStatement(sql);
- sta.setInt(1, id);
-
- ResultSet rs = sta.executeQuery();
-
- if(rs.next()) {
- int did = rs.getInt("id");
- String username = rs.getString("username");
- String address = rs.getString("address");
- System.out.println(did + "\t" + username + "\t" + address);
- }
-
- rs.close();
- sta.close();
- con.close();
- }
-
- }