使用SQLite数据库插入数据:
// 创建数据库表
String createTable = "CREATE TABLE IF NOT EXISTS tableName (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER)";
db.execSQL(createTable);
// 插入数据
ContentValues values = new ContentValues();
values.put("name", "John");
values.put("age", 25);
db.insert("tableName", null, values);
使用Room Persistence Library插入数据:
// 创建实体类
@Entity(tableName = "tableName")
public class MyEntity {
@PrimaryKey(autoGenerate = true)
public int id;
public String name;
public int age;
}
// 创建DAO接口
@Dao
public interface MyDao {
@Insert
void insert(MyEntity entity);
}
// 插入数据
MyEntity entity = new MyEntity();
entity.name = "John";
entity.age = 25;
myDao.insert(entity);
使用MySQLi扩展插入数据:
// 连接数据库
$connection = mysqli_connect("localhost", "username", "password", "database");
// 插入数据
$name = "John";
$age = 25;
$query = "INSERT INTO tableName (name, age) VALUES ('$name', $age)";
mysqli_query($connection, $query);
使用PDO插入数据:
// 连接数据库
$dsn = "mysql:host=localhost;dbname=database";
$connection = new PDO($dsn, "username", "password");
// 插入数据
$name = "John";
$age = 25;
$query = "INSERT INTO tableName (name, age) VALUES (?, ?)";
$statement = $connection->prepare($query);
$statement->execute([$name, $age]);
使用JDBC插入数据:
// 连接数据库
String url = "jdbc:mysql://localhost:3306/database";
String username = "username";
String password = "password";
Connection connection = DriverManager.getConnection(url, username, password);
// 插入数据
String name = "John";
int age = 25;
String query = "INSERT INTO tableName (name, age) VALUES (?, ?)";
PreparedStatement statement = connection.prepareStatement(query);
statement.setString(1, name);
statement.setInt(2, age);
statement.executeUpdate();