使用JDBC添加带参数的数据

import  java.sql.Connection;
import  java.sql.DriverManager;
import  java.sql.ResultSet;
import  java.sql.SQLException;
import  java.sql.Statement;

public   class  TestDML2  {

    
public static void main(String[] args) {
        
if(args.length != 3{
            System.out.println(
"Parameter Error! Please Input Again!");
            System.exit(
-1);
        }

        
        
int userId = 0;
        
try {
            userId 
= Integer.parseInt(args[0]);
        }
 catch (NumberFormatException e) {
            System.out.println(
"Parameter Error! Deptid should be Number Format!");
            System.exit(
-1);
        }

        
        String userName 
= args[1];
        String userAddress 
= args[2];
        
        Statement stmt 
= null;
        Connection conn 
= null;
        
try {
            Class.forName(
"com.mysql.jdbc.Driver");
            String url 
= "jdbc:mysql://localhost/data?user=root&password=123456";
            conn 
= DriverManager.getConnection(url);
            stmt 
= conn.createStatement();
            String sql 
= "insert into dept2 values (" + userId + ",'" + userName + "','" + userAddress + "')";
            System.out.println(sql);
            stmt.executeUpdate(sql);
        }
 catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
 catch (SQLException e) {
            e.printStackTrace();
        }
 finally {
            
try {
                
if(stmt != null{
                    stmt.close();
                    stmt 
= null;
                }

                
if(conn != null{
                    conn.close();
                    conn 
= null;
                }

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

        }

    }


}

 

你可能感兴趣的:(j2ee技术)