I have been able to link PostgreSQL to java. I have been able to display all the records in the table, however I unable to perform delete operation.
Here is my code:
con = DriverManager.getConnection(url, user, password);
String stm = "DELETE FROM hostdetails WHERE MAC = 'kzhdf'";
pst = con.prepareStatement(stm);
pst.executeUpdate();
Please note that MAC is a string field and is written in capital letters. This field does exist in the table.
The error that I am getting:
SEVERE: ERROR: column "mac" does not exist
When it comes to Postgresql and entity names (Tables, Columns, etc.) with UPPER CASE letters, you need to "escape" the word by placing it in "". Please refer to the documentation on this particular subject. So, your example would be written like this:
String stm = "DELETE FROM hostdetails WHERE \"MAC\" = 'kzhdf'";
On a side note, considering you are using prepared statements, you should not be setting the value directly in your SQL statement.
con = DriverManager.getConnection(url, user, password);
String stm = "DELETE FROM hostdetails WHERE \"MAC\" = ?";
pst = con.prepareStatement(stm);
pst.setString(1, "kzhdf");
pst.executeUpdate();
Related
I never asked any questions on stackoverflow but it already brought me tons of answers !
But this time, after some extended research, I have to ask it myself.
I'm using VB.Net with Sqlite and my query doesn't return any value when I execute it with parameters. I guess this has something to do with the fact SituationString contains commas but I really can't figure it out.
Here's is my code :
dim ChildCtx as Integer
dim SituationString as String
SituationString="968,970,978,979,980,981,995,1022,1099,1119"
With DataBase
.SQL_CMD.Parameters.Clear()
.SQL_CMD.CommandText = "SELECT SERVCTX_NO FROM SERVCTX WHERE SERVCTX_NO IN (#situationstring) AND MASTER = '1'"
.SQL_CMD.Parameters.Add("#situationstring", SqlDbType.VarChar, 255).Value = SituationString
ChildCtx = .SQL_CMD.ExecuteScalar
.SQL_CMD.Parameters.Clear()
End with
Connection is open and query works out fine if I write the whole query into one string.
Thanks,
You are mixing two techincs: merging constant data into SQL command and using parameters to pass data.
I suppose SituationString is a list of integer you expect for SERVCTX_NO.
So, you must merge it into statement:
.SQL_CMD.CommandText = "SELECT SERVCTX_NO FROM SERVCTX WHERE SERVCTX_NO IN ("+SituationString+") AND MASTER = '1'"
ChildCtx = .SQL_CMD.ExecuteScalar
Using parameters, as you did, SERVCTX_NO would be expected to be a string with 968,970,978,979,980,981,995,1022,1099,1119 exact content!
I am trying to send a SQL prepared statement to MySQL DB. This is what I have:
String sql1 = "SELECT idReimbursed_Funds As idReimFunds FROM reimbursedfunds Where ReimFundsName = ? AND Date = ?";
PreparedStatement pstmt1 = conn.prepareStatement(sql1);
pstmt1.setString(1, reimfund.getReimFundsName());
pstmt1.setDate(2, (Date) reimfund.getDate());
ResultSet rs1 = pstmt1.executeQuery(sql1);
while(rs1.next()){
idReimFunds = rs1.getInt("idReimFunds");
}
After googling this problem, I found solutions to use parenthesis around the question marks or the whole where clause such as:
String sql1 = "SELECT idReimbursed_Funds As idReimFunds FROM reimbursedfunds Where (ReimFundsName = ?) AND (Date = ?)";
This didn't work though. I get the same error message that is generated by my original code:
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?) AND (Date = ?)' at line 1.
When I try the SQL statement in MySQL Workbench is works fine. Is there a way to use 2 where clauses with JDBC? I know in other posts people have answered that it has to be sent as two different queries, but I thought I would ask just in case someone else reads this posts and knows of a way. Thank you!
The problem (apart from the Date issue as mentioned by bgp), is the line:
ResultSet rs1 = pstmt1.executeQuery(sql1);
You are trying to execute a query string on a prepared statement, which is not allowed by the JDBC standard (MySQL should actually throw an exception instead of sending it to the server as it currently does, but the end result is the same). The documentation of Statement.executeQuery(String sql) says:
Throws:
SQLException - if a database access error occurs, this method is called on a closed Statement, the given SQL statement produces anything other than a single ResultSet object, the method is called on a PreparedStatement or CallableStatement
(emphasis mine)
The reason is that you want to execute the prepared statement, not any other query. You should call PreparedStatement.executeQuery() (so without a parameter):
ResultSet rs1 = pstmt1.executeQuery();
Pretty sure this is because "Date" is a MySQL keyword (reserved). Call the field something else or escape it with backticks, i.e. `Date`
I have the following piece of code:
String sql = "SELECT * FROM users WHERE email = " + email;
prestat = DBConnection.prepareStatement(sql);
rs = prestat.executeQuery();
boolean isEmpty = !rs.first();
if (isEmpty) {
// Special marker for nonexistent user
return "$null";
} else if (password.equals(rs.getString(2))) {
String uuid = UUID.randomUUID().toString();
// Here I want to insert the UUID into the database
}
Considering that I have already searched the database, I'm wondering if there is a way I can get the row number/position,and use it to update the UUID column, hence preventing another DB search.
It's not clear what you are trying to do here, and it doesn't really seem you understand what goes on. For example, when using a prepared statement, one doesn't feed it with two concatenated strings, but instead does:
PreparedStatement stmt =
conn.prepareStatement("SELECT * FROM foo WHERE bar = ?");
stmt.setString(1, "Hello World!");
Then, if you really want to avoid the double search, you can simply assume an optimistic point of view:
UPDATE users SET uuid = ? WHERE email = ? AND password = ?
Ensure that the email is unique, by the way. Also, maybe you already do it, but don't save plaintext passwords in the db. Use cryptographic hashes instead, and salt them.
Since you specify that your backend is Apache Derby, maybe this guide can help you solve your problem (it's 100% Java but not truly portable because of different backends may not implement all of the required features). Basically, you pass two flags when preparing the statement:
Statement stmt = con.createStatement(
ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_UPDATABLE);
ResultSet res = stmt.executeQuery("SELECT * FROM users WHERE email = ?");
and then you have a ResultSet backed by an updateable cursor, so you can call:
res.updateString("uuid", uuid);
res.updateRow();
I think this may avoid the additional search, however I didn't test it and cannot say if there's a real performance gain. Sounds like premature optimization, though.
well you could simply replace
prestat = DBConnection.prepareStatement("SELECT * FROM users WHERE email =" + email);
by
prestat = DBConnection.prepareStatement("Update users set uuid = '" + uuid + "' WHERE email =" + email);
And of course execute.
SQL Server 2005. Visual Studio 2010. ASP.NET 2.0 Web Application
This is a web application that supports multiple languages, one of them is Korean. I have “langid” in the query string to differentiate different languages, if langid=3 it is Korean.
In my code behind’ C# code, I read a table using this query:
"select * from Reservations where rsv_id = 1234"
There is a column named "rsv_date" in the table which is reservation date, of type datetime. In the db table its value is "11/22/2012 4:14:37 PM". I checked this in SQL server management studio. But when I read it out, I got "2012-11-22 오후 4:14:37"! Where does that Korean “오후” come from??? Is it because of some culture setting anywhere? But I don’t see where, either in my code or in SQL Server. This caused problem for me, because when I modify this record, it will try to write "2012-11-22 오후 4:14:37" to the db, which of course SQL server reports error.
My original code:
Hashtable reservation = new Hashtable();
SqlCommand sqlCommand = null;
SqlDataReader dataReader;
string queryCommand = "select * from Reservations where rsv_id = #RsvID";
sqlCommand = new SqlCommand(queryCommand, getConnection());
sqlCommand.Connection.Open();
sqlCommand.Parameters.AddWithValue("#RsvID", rsvID);
dataReader = sqlCommand.ExecuteReader();
while (dataReader.Read())
{
reservation["rsvID"] = dataReader["rsv_id"];
reservation["rsvCode"] = dataReader["rsv_code"];
reservation["rsvType"] = dataReader["rsv_type"];
reservation["rsvDate"] = dataReader["rsv_date"]; // where does Korean come from?
...
}
It's a common misunderstanding that you can "check" the format of datetime fields in the database.
The format you see on screen will always depend on the client, even if the client is "SQL server management studio".
In the database, the datetime is stored in a binary format that very few need to know.
So, the Korean characters are from the client, in this case your own program.
And Yes, they will depend on some culture setting somewhere.
Your example doesn't show what happens to reservation["rsvDate"] , where is the value displayed with the Korean characters ?
How are you trying to write the value with Korean characters to the database ?
To avoid Korean characters you could use .ToString(CultureInfo.InvariantCulture) where you use the Date value.
I'm getting a strange syntax error when I run this in VB:
SQLString = "UPDATE Login SET Password = '" + PasswordTextBox.Text + "'"
SQLString += " WHERE UserName = '" + UserNameTextBox.Text + "'"
The Username is checked before getting to this part and is definitly in the database.
It gives an exception saying that there's a syntax error in update statement. Anyone have any idea what's wrong?
LOGIN is a reserved word in SQL Server (used for login account management), so in order to use it in a query (i.e. a column name) you need to escape it with [], so use [LOGIN] as the field name.
You should never use string concatenation and pass that to your SQL database, as you are exposing yourself to SQL Injection attacks.
You should use the SqlCommand object and pass through parameters. See this article on how to do so.
SQLString = "UPDATE [Login] SET Password = #password "
SQLString += " WHERE UserName = #userName"
...
dbCommand.Parameters.Add("#password", SqlDbType.VarChar, 50)
dbCommand.Parameters["#password"].Value = PasswordTextBox.Text
dbCommand.Parameters.Add("#userName", SqlDbType.VarChar, 50)
dbCommand.Parameters["#userName"].Value = UserNameTextBox.Text
I am pretty sure that Login is a reserved word, try changing Login to [Login]
Password is a reserved word so [Password] fixes it, my lecturer fixed to for me :)
Instead of showing how you're building the statement, show us what's in SQLString when the statement is executed.
Also, try enclosing the column and table names in the identifier quote characters, which are [ and ] for Microsoft, and ` (on the tilde key) for many others databases.
Without knowing what you are using for your actual password and username, my guess is that some character in one (or both) of those are causing the sql statement to end prematurely. You should really use parameters when executing sql like this.
Take a look at this: http://msdn.microsoft.com/en-us/library/ms998271.aspx
I agree with some of the previous answers, about using parameters (I gave + 1 to #Oded) and using [ ] with tablenames and fieldnames (I gave +1 to SQLMenace).
In conclussion, I think this is the most correct way to launch your query:
using(SqlConnection connection = new SqlConnection("<your connection string>"))
{
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "UPDATE [Login] SET [Password] = #PasswordParameter WHERE [UserName] = #UserNameParameter";
command.Parameters.AddWithValue("#PasswordParameter", PasswordTextBox.Text);
command.Parameters.AddWithValue("#UserNameParameter", UserNameTextBox.Text);
command.ExecuteNonQuery();
}
I would recommend surrounding the words "login" and "password" with tick marks to let the handler know that they are not to be rendered as reserved words.
So:
Update 'login' SET 'password'
But rather than single-quotes, use the tick mark (upper-left key on the keyboard). I can't demonstrate it correctly as StackOverflow will treat it as a class if it's surrounded in tick marks.