簡體   English   中英

如何使用變量查詢數據庫? 動態SQL ...?

[英]How do you query database using a variable? Dynamic SQL…?

我想知道如何在SQL查詢中使用給定的變量或數組搜索數據庫表。 我目前正在使用Java和PostgreSQL,並且想要執行以下操作:

String word = "Apples";
SELECT * FROM table WHERE name = word;

要么

token[0] = "Apples";
SELECT * FROM table WHERE name = token[0};

有人知道這樣做的正確方法嗎?

我的最終目標只是檢查數據庫,以查看是否將用戶輸入的單詞存儲在數據庫中,如果使用該單詞,則對該單詞執行某些操作。

使用PrepareStatement像,

String word = "Apples";
PreparedStatement st = conn.prepareStatement("SELECT * FROM table WHERE name = ?");
st.setString(1, word);
ResultSet rs = st.executeQuery();

如果要在Java端獲取數據,請執行以下操作:

Connection con = DriverManager.getConnection
  ("jdbc:derby://localhost:1527/testDb","name","pass");
  PreparedStatement updateemp = con.prepareStatement
  ("insert into emp values(?,?,?)");
  updateemp.setInt(1,23);
  updateemp.setString(2,"Roshan");
  updateemp.setString(3, "CEO");
  updateemp.executeUpdate();
  Statement stmt = con.createStatement();
  String query = "select * from emp";
  ResultSet rs =  stmt.executeQuery(query);

查看完整細節: 這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM