写一个万能的效验常见字段的java,并且把数据存入库
时间: 2024-03-03 09:48:01 浏览: 148
以下是一个简单的万能效验常见字段并将数据存入数据库的 Java 代码示例:
```java
import java.sql.*;
public class Validator {
// Connection to the database
private Connection conn;
// Constructor to initialize the database connection
public Validator() {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username", "password");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
// Method to validate and store data in the database
public boolean validateAndStore(String fieldValue, String fieldType) {
if (fieldValue == null || fieldValue.isEmpty()) {
return false;
}
switch (fieldType.toLowerCase()) {
case "email":
if (isValidEmail(fieldValue)) {
storeData(fieldValue, fieldType);
return true;
} else {
return false;
}
case "phone":
if (isValidPhoneNumber(fieldValue)) {
storeData(fieldValue, fieldType);
return true;
} else {
return false;
}
case "zipcode":
if (isValidZipCode(fieldValue)) {
storeData(fieldValue, fieldType);
return true;
} else {
return false;
}
// Add more cases for other field types as needed
default:
storeData(fieldValue, fieldType); // If fieldType is not recognized, store the data anyway
return true;
}
}
// Method to validate email format
private boolean isValidEmail(String email) {
// Regular expression pattern for validating email addresses
String pattern = "^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$";
return email.matches(pattern);
}
// Method to validate phone number format
private boolean isValidPhoneNumber(String phone) {
// Regular expression pattern for validating US phone numbers
String pattern = "^\\(\\d{3}\\) \\d{3}-\\d{4}$";
return phone.matches(pattern);
}
// Method to validate zip code format
private boolean isValidZipCode(String zip) {
// Regular expression pattern for validating US zip codes
String pattern = "^\\d{5}(-\\d{4})?$";
return zip.matches(pattern);
}
// Method to store data in the database
private void storeData(String fieldValue, String fieldType) {
try {
PreparedStatement stmt = conn.prepareStatement("INSERT INTO mytable (field_value, field_type) VALUES (?, ?)");
stmt.setString(1, fieldValue);
stmt.setString(2, fieldType);
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
该代码与上面的代码类似,但添加了一个数据库连接和一个 `storeData` 方法来将数据存储到数据库中。`validateAndStore` 方法验证字段并在验证成功后将数据存储到数据库中。如果字段类型未被识别,则数据将存储在数据库中,而不进行任何验证。
请注意,示例代码中的数据库连接和查询语句是简单的示例,实际使用时需要根据您的具体情况进行修改和扩展。
阅读全文