Im working with MySQL in java.
I'm trying to update the 'owners' field in one of the tables 'regApartmentsTable', 'gardApartmentsTable', 'penthousesTable', which is empty, and corresponds to specific apartmentNum and street, and replace it with the string 'newOwners'.
In order to do that I've wrote the following code:
st=connection.prepareStatement("UPDATE regApartmentsTable,gardApartmentsTable,penthousesTable SET owners=? " +
"WHERE owners=? AND apartmentNum=? AND street=?");
st.setString(1, newOwners);
st.setString(2, "");
st.setInt(3, apartmentNum);
st.setString(4, streetName+" "+buildingNum);
I include the 3 tables since I need to look in all of them. (The required apartment, which has no owners, and matches the apartmentNum and street, cannot be in more than one table, if it helps anyone).
But, when I try to run this code, I get a "Column 'owners' in field is ambiguous" error.
Any ideas how else should I write the SQL command ?
thanks ahead!
EDIT:
I didn't get a sufficient answer to my problem... Ok, I understood that the exception raises since 'owners' field is common in those three tables.
And yet, how do I solve the problem? I cannot add a prefix with the table's name since I do not know in which table I'm going to find the required apartment... If I knew so, I wouldn't have searched in 3 tables.
The multiple tables UPDATE in MySQL is just a form of table join, using regApartmentsTable.owners and such.
You need a separate UPDATE for every table here, as a join is not what you intend for the update. Or make a base table.
str = connection.prepareStatement("UPDATE regApartmentsTable SET owners=? " +
"WHERE owners=? AND apartmentNum=? AND street=?");
str.setString(1, newOwners);
str.setString(2, "");
str.setInt(3, apartmentNum);
str.setString(4, streetName+" "+buildingNum);
str = connection.prepareStatement("UPDATE gardApartmentsTable SET owners=? " +
"WHERE owners=? AND apartmentNum=? AND street=?");
stg.setString(1, newOwners);
stg.setString(2, "");
stg.setInt(3, apartmentNum);
stg.setString(4, streetName+" "+buildingNum);
stp = connection.prepareStatement("UPDATE penthousesTable SET owners=? " +
"WHERE owners=? AND apartmentNum=? AND street=?");
stp.setString(1, newOwners);
stp.setString(2, "");
stp.setInt(3, apartmentNum);
stp.setString(4, streetName+" "+buildingNum);
Related
Hi there i have this code which is having an error when i try to run it.
s.executeUpdate("UPDATE [salesRecord] SET [backOrder] = 'backOrder'," +
" [quantity] ='"+ conDiff +"'" +
"WHERE [productID] = '" + s1 +"' AND [orderNumber] = '"+valueOrder+"' " );
the purpose of this code is to set orders as back orders when all items are not delivered. i want to specify which product i will update by setting my where to look for that item using productID and orderNumber.
java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver]
Too few parameters. Expected 1.
at sun.jdbc.odbc.JdbcOdbc.createSQLException(Unknown Source)
Above is the error that shows when i try to run the program.
Try the following
Let backOrder , conDiff , s1, valueOrder be the variables.
s.executeUpdate("UPDATE [salesRecord] SET [backOrder] = '"+backOrder+"',[quantity] ='"+ conDiff +"' WHERE [productID] = '" + s1 +"' AND [orderNumber] = '"+valueOrder+"' " );
The query you have written is not using any parameters, but the error message says it is expecting one. This means that your "s" is probably being reused from somewhere else before and, that is using a parameter.
Seeing as you are using Java, I assume s is a java.sql.PreparedStatement or similar and that a parameter has been set using any one of the s.setXXX(parameterIndex, value) methods.
more details see http://docs.oracle.com/javase/7/docs/api/index.html
The simple solution is to use new statement.
I made a query in Java which changes one column's datatype in another. It works fine until it tries to change type. It finds all columns in DB with specified datatype, but cannt change it.
Here is my code:
st = conn.createStatement();
rs = st.executeQuery("SELECT a.name as ColName, o.name AS TableName"
+ "FROM sys.syscolumns AS a"
+ "INNER JOIN sys.systypes AS b ON a.xtype = b.xtype AND b.name = 'char' AND a.length = 255"
+ "INNER JOIN sys.objects AS o ON a.id = o.object_id WHERE (o.type = 'u') AND (o.schema_id = 1)");
ResultSet rsPom;
while (rs.next()){
String tName=rs.getString("TableName");
String cName=rs.getString("ColName");
System.out.println(tName+" "+cName);
rsPom=st.executeQuery("ALTER TABLE "+ tName+" ALTER COLUMN "+cName+" nvarchar(255)");
}
And here is my Exception:
com.microsoft.sqlserver.jdbc.SQLServerException: The object 'CK_TimeInstant_frame_default' is dependent on column 'frame'.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:216)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1515)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.doExecuteStatement(SQLServerStatement.java:792)
at com.microsoft.sqlserver.jdbc.SQLServerStatement$StmtExecCmd.doExecute(SQLServerStatement.java:689)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:5696)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1715)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:180)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:155)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeQuery(SQLServerStatement.java:616)
at DataTypeChanger.changeDataType(DataTypeChanger.java:50)
at DataTypeChanger.main(DataTypeChanger.java:36)
Does anyone knows what is all about, and what can I do?
Firstly, my apologies about the sarky comment above.
The reason you receive this error is because your alter script isn't taking any action with respect to constraints. Columns which are the target of constraints (Unique, Foreign Key, Default, etc) can't be modified unless the constraint is first dropped. In which case you'll probably need to add the constraints back afterwards.
I've assumed your earlier (deleted) comment still holds, viz that you do not require to create the constraints again after they have been dropped.
Re : How do I drop all constraints
Disclaimer : Back up your database before you try this, but the following MIGHT work. It is a destructive one way operation.
declare #sql nvarchar(2000);
while(exists(select 1 from sys.objects WHERE type_desc LIKE '%CONSTRAINT%'))
begin
BEGIN TRY
SELECT TOP 1 #sql=('ALTER TABLE ' + SCHEMA_NAME(schema_id) + '.[' + OBJECT_NAME(parent_object_id)
+ '] DROP CONSTRAINT [' + OBJECT_NAME(OBJECT_ID) + ']')
FROM sys.objects
WHERE type_desc LIKE '%CONSTRAINT%'
ORDER BY NEWID();
exec (#sql);
END TRY
BEGIN CATCH
END CATCH
end;
GO
Rationale: The TRY CATCH is required because there is no guarantee that we will get the order of dependencies correct when dropping constraints (e.g. FK dependent on PK), so we basically squash the error and try drop another random constraint (ORDER BY NEWID())
Reference : Based on this query here, but extended to all constraints
SqlFiddle Here
I am using an sql query to add data data to an existing database table.
I want to add data under the columns 'Room_Resource' and 'Quantity'.
The system is designed to allow bookings and i am trying to add bookings made to a tblBookings table, the code below is taken from JButton clicked function.
The value I want to add to Room_Resource is a name taken from a selected table within the system. I declared a variable for this 'resourceChosenString'
The value I want to add to quantity is from the 'Quantity' variable i have declared in relation to a combo box.
Here are my declarations:
int selectedResourceRow = tblResources.getSelectedRow();
Object resourceChosen = tblResources.getValueAt(selectedResourceRow,1);
String resourceChosenString = resourceChosen.toString();
int Quantity = cmbQuantity.getSelectedIndex();
I then have a sql statement:
String sql = ("INSERT INTO tblBookings (Room_Resource,Quantity) VALUES (" + resourceChosenString + " ', ' " + Quantity + " ',) ");
And then the execute code:
try{
pst = conn.prepareStatement(sql);
pst.execute();
JOptionPane.showMessageDialog(null, "Added");
} catch (Exception e){
JOptionPane.showMessageDialog(null, "Error Adding Booking");
}
Currently it gives me an error when I attempt to add the data to the table and wondered if anyone had any suggestions?
Also I considered that perhaps the problem could lie in the fact I have more than two columns in the external table and the table I am adding the data to so columns could be left blank. If this could be the problem, could anyone tell me how to get around it? Possibly if there is a null function I can use instead of values.
You probably want to tell us what database you're using and what error message you're getting. But just off the bat, it looks like your sql string is not formatted correctly. I don't know if you mistyped it in the question or if your code has a simple syntax error.
Just shooting from the hip with what you have, it looks like your sql statement should be:
String sql = "INSERT INTO tblBookings (Room_Resource,Quantity) VALUES ('" + resourceChosenString + "', " + Quantity + ")";
Notice that resourceChosenString should be wrapped in single quotes (you're missing the single quote on the left). Also, I don't think you're supposed to wrap a number in single quotes (I could be wrong since I don't know which database you're using).
Qwerky is right though; you should use a PreparedStatement.
The SQL you are generating is not valid and looks like this;
INSERT INTO tblBookings (Room_Resource,Quantity) VALUES (resource ', ' 1 ',)
^ ^
missing quote extraneous comma
You should tidy it up, or better still use a PreparedStatement.
String sql = "insert into tblBookings (Room_Resource,Quantity) values (?, ?)";
PreparedStatement pst = conn.prepareStatement(sql);
pst.setString(1, resourceChosenString);
pst.setInt(2, quantity); //variable names are not capitalised by convention
pst.execute();
So I am coding in Java, using JDBC with SQL to get data from a database. I cannot chnage the data or the column names in the database. Everything worked perfectly until I was told today that another column of the database was needed.
So I tried to add the column name to the select statement, however I get an error:
"java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 2."
Here is the variable and name for the column: String est = "\"Estimates Complete?\"";
So after LOTS of research, it seems that there is something called "Bind Variables" in JDBC and ? happens to be one of them. I keep finding forum posts and answers on how to create Bind Variables, but nothing on how to "Escape" them. I cannot change the value of the Estimates Complete? column, and it is needed for my program.
If I try String est = "Estimates Complete?";, then the error I get is:
java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver]COUNT field incorrect
Anyone know if it is possible? Thanks.
Edit: Code example:
Statement s = conn.createStatement();
String tableName = "\"Open WRs V2\"", data1 = "\"Project Name\"",est = "Estimates Complete?";
String selTable = "SELECT " + data1 + "," + est+ " FROM " + tableName;
s.execute(selTable);
ResultSet rs = s.getResultSet();
while ((rs.next())) {
String name = (rs.getString(1));
String estimate= rs.getString(2);
System.out.println("test: "+estmate);
}
s.close();
can you replace the ? with chr(63) like in the answer here :
How to avoid ODBC parameterization for the question mark character ? within literals and comments?
preparedStatement = connection.prepareStatement("select fname,lname, "
+ "sportman_code,start,finish,salary,amount,number,pnumber "
+ "from sportman,customer "
+ "where customer.customer_code = "
+ "sportman.customer_code order by ? limit ?,?");
preparedStatement.setString(1, "fname");
preparedStatement.setInt(2, 0);
preparedStatement.setInt(3, 9);
resultSet = preparedStatement.executeQuery();
order by didn't work.
why?
when i put fname instead ? it work correctly.
"sportman.customer_code order by fname limit ?,?");
how can i do that?
Your ORDER BY works, but not as you expect it to. When you use
preparedStatement.setString(1, "fname");
it will make an ORDER BY like this
ORDER BY 'fname'
and not as you expect
ORDER BY fname
The code in your question will then be like sorting a package of M&Ms alphabetically
You can't bind in identifiers like table names or column names, only values that you want to insert, compare, etc
Binding works for literals in the query, not for keywords or identifiers. You'll need to use another approach for sanitizing the sort field if you want it to be dynamic.