primarykey.java

来自「网上商城 1.注册登录 2.商品浏览 3.购物车 4.订单」· Java 代码 · 共 95 行

JAVA
95
字号
package manager;
import java.sql.*;

public class PrimaryKey {
    private static Object initlock=new Object();
    private static PrimaryKey primarykey=null;

    public static PrimaryKey getInstance(){
        if(primarykey == null){
            synchronized (initlock){
                if(primarykey==null){
                    try{
                        primarykey=new PrimaryKey();
                    }catch(Exception e){
                        e.printStackTrace();
                    }
                }
            }
        }
        return primarykey;
    }

    private static int getKeyByTableName(String _tablename){
        String driver = "org.gjt.mm.mysql.Driver";
        String url = "jdbc:mysql://localhost:3306/dstore";
        String username = "root";
        String password = "123";


        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;

        int key=0;

        try {
            
            int pluskey=0;
            Class.forName(driver);
            con = DriverManager.getConnection(url, username, password);
            con.setAutoCommit(false);
            String sql = "select newId from primaryKey where tablename='"+
                         _tablename+"'";
            stmt = con.createStatement();
            rs=stmt.executeQuery(sql);
            while (rs.next()){
                key=rs.getInt("newId");
            }
            pluskey= key + 1 ;
            sql ="update primaryKey set newId='"+pluskey+"'where tablename='"+_tablename+"'";
            stmt.executeUpdate(sql);
            con.commit();
            con.setAutoCommit(true);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (con != null) {
                try {
                    rs.close();
                    stmt.close();
                    con.close();

                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return key;
    }

    public Integer getUserKey(){
        int n=PrimaryKey.getKeyByTableName("user");
        return new Integer(n);
    }

    public Integer getOrderInfoKey(){
       int n=PrimaryKey.getKeyByTableName("orderInfo");
       return new Integer(n);
   }

   public Integer getOrderProductKey(){
       int n=PrimaryKey.getKeyByTableName("orderProduct");
       return new Integer(n);
   }

   public Integer getProductKey(){
       int n=PrimaryKey.getKeyByTableName("product");
       return new Integer(n);
   }
   public static void main(String args[]){
       System.out.println(PrimaryKey.getInstance().getUserKey());
   }

}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?