我無法將緯度和經度值保存到 SQLite 資料庫中。它們是什么型別的資料?我嘗試將它們作為 REAL、BLOB、NUMERIC 和 TEXT 插入,但它們沒有正確保存。這是我的代碼:
const createTable = () => {
db.transaction((tx) => {
tx.executeSql(
"CREATE TABLE IF NOT EXISTS "
"Users "
"(ID INTEGER PRIMARY KEY AUTOINCREMENT, Title TEXT, Description TEXT, Latitude TEXT);"
)
})
}
//in the following function I want to insert Latitude into Users and display it in the console.log
const setData = async () => {
try {
dispatch(setTitle(title));
Geolocation.getCurrentPosition(info => dispatch(setLat(info.coords.latitude)));
console.log('latitudine:',lat); // i have my current latitude
await db.transaction(async (tx) => {
await tx.executeSql(
"INSERT INTO Users (Title, Latitude) VALUES (?,?)",
[title, lat]
);
});
await db.transaction(async (tx) => {
await tx.executeSql(
"SELECT Title, Latitude FROM Users",
[],
(tx, results) => {
len = results.rows.length;
if (len > 0) {
for (let i=0;i<len;i ){
var userTitle = results.rows.item(i).Title;
var userLatitude = results.rows.item(i).Latitude;
console.log('userTitle: ',userTitle); // no display
console.log('Latitude from database: ',userLatitude); //no display
}
}
}
)
});
} catch (error) {
console.log(error);
}
}
如果我不在資料庫中添加緯度列,則該函式可以正常作業并userTitle正確顯示。我認為問題來自緯度的列型別,但我不確定這一點。有人可以幫我嗎?很感謝!
編輯:如果我只有 3 列(ID、標題、緯度)并且緯度將值保存為字串,我沒有問題(感謝 Hitesh Prajapati!)。但是...如果我在資料庫中添加一列(例如經度),我又遇到了問題。特別是當我必須在經度列中插入新值時。我該如何解決這個問題?謝謝
uj5u.com熱心網友回復:
正如 Hitesh Prajapati 在對該問題的評論中所建議的那樣,緯度需要在保存在 SQLite 資料庫中之前轉換為字串 - 基于為其列定義的型別。
從檔案中,getCurrentPosition回傳一個物件,其coords屬性是GeolocationCoordinates物件,其longitude和latitude欄位為雙精度型別。
因此,如果您將緯度的列定義為Latitude TEXT,則需要將緯度轉換為字串。如果列型別設定為 TEXT ,則經度列也需要相同的內容:
...
// This assumes lat is assigned the value from info.coords.latitude
// And longitude is assigned the value from info.coords.longitude
await tx.executeSql(
"INSERT INTO Users (Title, Latitude, Longitude) VALUES (?,?)",
[title, lat.toString(), longitude.toString()]
);
...
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/376725.html
