import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;
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];
PreparedStatement pstmt = 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);
pstmt = conn.prepareStatement("insert into dept2 values (?, ?, ?)");
pstmt.setInt(1, userId);
pstmt.setString(2, userName);
pstmt.setString(3, userAddress);
pstmt.executeUpdate();

} catch (ClassNotFoundException e) ...{
e.printStackTrace();
} catch (SQLException e) ...{
e.printStackTrace();
} finally ...{
try ...{
if(pstmt != null) ...{
pstmt.close();
pstmt = null;
}
if(conn != null) ...{
conn.close();
conn = null;
}
} catch (SQLException e) ...{
e.printStackTrace();
}
}
}
}
本文提供了一个使用 Java 进行 SQL 操作的例子,展示了如何通过传递参数插入数据到 MySQL 数据库中的 dept2 表。
4360

被折叠的 条评论
为什么被折叠?



