Hello everyone i am trying to run a simple query on a long number i have tried but still returns me id type is long integer. I am getting all the data a jTable and the 1st column is of id when i ever click on the row it always gives me this exception and i have got the correct value from table when printed in console
java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Data type mismatch in criteria expression.
My code is :
int row = recordsTable.getSelectedRow();
String tableValue = (recordsTable.getModel().getValueAt(row, 0).toString());
String qry = "Select * from records where id ='" + Long.parseLong(tableValue) + "'";
try {
db.setStmt((Statement) db.getCon().createStatement());
ResultSet rs = ((java.sql.Statement) db.getStmt()).executeQuery(qry);
if (rs.next()) {
id=rs.getLong("id");
idTextField.setText(Long.toString(id));
customerCode = rs.getString("customer_code");
custCodeTextField.setText(customerCode);
firstName = rs.getString("first_name");
firstTextField.setText(firstName);
lastName = rs.getString("last_name");
lastTextField.setText(lastName);
customerContact = rs.getString("customer_mobile");
custMobTextField.setText(customerContact);
customerAddress = rs.getString("customer_address");
custAddressTextField.setText(customerAddress);
fillComboBox();
area=rs.getString("area");
areaComboBox.setSelectedItem(area);
payment_this_month = rs.getInt("payment");
paymentTextField.setText(Integer.toString(payment_this_month));
duePayment = rs.getInt("balance");
balTextField.setText(Integer.toString(duePayment));
java.util.Date dateSet = rs.getDate("bill_issued_on");
billTextField.setText(dateSet.toString());
connectionStatus = rs.getString("connection_status");
jComboBox2.setSelectedItem(connectionStatus);
Remove the single quotes around
'" + Long.parseLong(tableValue) + "'"
Related
Basically there is a table with the fields: id(PK), name, total of votes.
And I need to add 1 vote for this specific id per turn the program is used, I was intending to only get the total votes of this id, add plus 1 vote and store it again in the same id. I was using this code:
String user = "root";
String pass = "";
String url = "jdbc:mysql://127.0.0.1:3306/provapaoo_22_06_2018";
String takeVotes = String.format("select `Total Votes` "
+ "from `%s` where id= ?", nameOfTable);
String addVote = String.format("update `%s` set "
+ "`Total votes` = ?", nameOfTable);
try{
Connection conec =
DriverManager.getConnection(url, usuario, senha);
PreparedStatement comand =
conexão.prepareStatement(takeVotes);
comando.setInt(1, id);
ResultSet result = comand.executeQuery();
int qtdVotes = 0;
while(resultado.next()){
qtdVotes = result.getInt("Total Votes");
}
qtdVotes++;
comand = conec.prepareStatement(addVote);
comand.setInt(1, qtdVotes);
comand.executeUpdate();
comand.close();
conec.close();
}catch(SQLException e){
e.printStackTrace();
}
The program is running good but the problem is the resultSet, it's not returning only the total votes of that id, it's returning the total votes of everyone, it's almost like the sql syntax isn't working.
Sorry, I was an idiot, It was indeed the sql syntax who was wrong.
Here's the one I used now.
String addVote = String.format("update `%s` set "
+ "`Total votes` = ? where id = ?", nameOfTable);
Thank everyone anyway
I have used this method without using the join in the query and it was working as expected. But I added a inner join and now it can't update the "used" column
public HashMap<String, Comparable> getPhoneNumberAndMarkAsUsed() {
String[] colNames = { "phone_number.id", "phone_number.phone_number",
"phone_number.account_id", "phone_number.used AS used",
"(now() AT TIME ZONE account.timezone)::time AS local_time" };
String query = "select " + Stream.of(colNames).collect(Collectors.joining(", "))
+ " from account INNER JOIN phone_number ON account.id = phone_number.account_id where phone_number.used = false order by id DESC limit 1 for update";
HashMap<String, Comparable> account = new HashMap<String, Comparable>();
try (Connection conn = DriverManager.getConnection(url, props); // Make sure conn.setAutoCommit(false);
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery(query)) {
conn.setAutoCommit(false);
ResultSetMetaData rsmd = rs.getMetaData();
int columnsNumber = rsmd.getColumnCount();
while (rs.next()) {
for (int i = 1; i <= columnsNumber; i++) {
if (i > 1)
System.out.print(", ");
String columnValue = rs.getString(i);
System.out.print(columnValue + " " + rsmd.getColumnName(i));
}
// Get the current values, if you need them.
account.put("phone_number", rs.getString("phone_number"));
account.put("account_id", rs.getLong("account_id"));
rs.updateBoolean("used", true);
rs.updateRow();
}
conn.commit();
} catch (SQLException e) {
e.printStackTrace();
}
return account;
}
the loop prints the following
7223 id, 10001234567 phone_number, 1093629 account_id, f used, 23:32:42.502472 local_time
accourding to the output above, then I am use that column "used" is part of the ResultSet. But I get the following Exception
org.postgresql.util.PSQLException: ERROR: column "used" of relation "account" does not exist
This is the query when printed
select phone_number.id, phone_number.phone_number, phone_number.account_id, phone_number.used AS used, (now() AT TIME ZONE account.timezone)::time AS local_time from account INNER JOIN phone_number ON account.id = phone_number.account_id where phone_number.used = false order by id DESC limit 1 for update
used belongs to the phone_number table not the account table. How can this be resolved?
here is the problem in your code:
rs.updateBoolean("used", true);
this statement will try to update the data of table through resultset but to do that you cannot user join and also there is one problem.
As you are updating via resultset it will try to update account table and if we find used column is account table then error occurs.
so your code is trying to find column "used" in account table but it is not there.
try this one:
String query = "select " + Stream.of(colNames).collect(Collectors.joining(", "))
+ " from phone_number INNER JOIN account phone_number ON account.id = phone_number.account_id where phone_number.used = false order by id DESC limit 1 for update";
I am trying to update my database table but I have encountered a MySQLSyntaxErrorException. May I know how can I solve this error?
Thanks ! :)
//Retrieve data from database
String queryy = "SELECT agent.agentID, agent.agentEmail, departmentName FROM agent JOIN department ON agentEmail = email";
rs = myStat.executeQuery(queryy);
//Iterate the result set and get one row at a time
while (rs.next()) {
int id = rs.getInt("agentID");
email = rs.getString("agentEmail");
String emaill = email;
departmentName = rs.getString("departmentName");
String departmentNamee = departmentName;
System.out.println("Agent ID = " + id);
System.out.println("Department Name = " + departmentNamee);
System.out.println("Email = " + emaill + newLine);
//Update agentID in department table from agent table
String departmentUpdateSql = "UPDATE department SET agentID = ?"
+ "VALUES ('" + id +"')";
myStat.executeUpdate(departmentUpdateSql);'
And this is the error that I got:
Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 '?VALUES ('23')' at line 1
sql update statements do not use the VALUES keyword (that is for inserts)
Use a PreparedStatement as below
String updateTableSQL = "UPDATE department SET agentID = ?"
PreparedStatement preparedStatement =
dbConnection.prepareStatement(updateTableSQL);
preparedStatement.setInt(1, id);
// execute update SQL stetement
preparedStatement.executeUpdate();
Note
I would imagine that you would also need some kind of where clause otherwise you will be updating all records
Ok I have this issue. I need to update a record on my DB but I am having trouble because of my SQL syntax. By pressing the "Update Name" button, 2 messages pop up and the user selects the former name and the new name for the Table. But the statement is never executed and the names wont change. My main goal is to "resolve" the id from the 1st statement to a variable
String name_1 = "SELECT id FROM consoles WHERE name LIKE ? ";
and add it here
String name = "UPDATE consoles SET name = ? WHERE id = ?";
Is it possible to resolve to a variable the id I get from my 1st statement?
try
{
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test1?user=me&password=12345");
String name_1 = "SELECT id FROM consoles WHERE name LIKE ? ";
String name = "UPDATE consoles SET name = ? WHERE name LIKE ?";
PreparedStatement psname = conn.prepareStatement(name);
PreparedStatement psname_1 = conn.prepareStatement(name_1);
String strin = JOptionPane.showInputDialog(null,"Previous Name : ");
String strout = JOptionPane.showInputDialog(null,"New Name : ");
psname.setString(1,strin);
psname.setString(2,"%" +strout+ "%");
psname_1.setString(1,"%"+strin+"%");
psname.executeUpdate();
Statement stmtname = conn.createStatement();
// show the updated table
ResultSet rsname = stmtname.executeQuery("SELECT * FROM consoles INNER JOIN hardware ON consoles.id=hardware.id");
.
.
.
ADDING THEM TO A JTABLE
.
.
.
Arguments are switched.
psname.setString(2,"%" +strout+ "%");
psname_1.setString(1,"%"+strin+"%");
should be
psname.setString(2, "%" + strin + "%");
psname_1.setString(1, strout);
try
{
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test1?user=me&password=12345");
String name = "UPDATE consoles SET name = ? WHERE name LIKE ?";
PreparedStatement psname = conn.prepareStatement(name);
String strin = JOptionPane.showInputDialog(null,"Previous Name : ");
String strout = JOptionPane.showInputDialog(null,"New Name : ");
psname.setString(1,strout);
psname.setString(2,"%" +strin+ "%");
psname.executeUpdate();
Statement stmtname = conn.createStatement();
// show the updated table
ResultSet rsname = stmtname.executeQuery("SELECT * FROM consoles INNER JOIN hardware ON consoles.id=hardware.id");
.
.
.
ADDING THEM TO A JTABLE
.
.
.
So I'm very new to java and SQL and they are my first programming languages. I am trying to do some work with JDBC. I want to allow for a user to input an id and return a query based on the variable. If someone could at least point me in the right direction... Here is the code I'm starting with. Mind you its crude but just trying to get a working piece of code so I can better implement it in my main class.
Scanner input = new Scanner(System.in);
Class.forName("org.sqlite.JDBC");
Connection conn =
DriverManager.getConnection("jdbc:sqlite:C:\\Users\\Derek\\Documents\\Databases\\example.sqlite");
Statement stat = conn.createStatement();
PreparedStatement prep1 = conn.prepareStatement(
"insert into MedType values (?, ?);");
PreparedStatement prep2 = conn.prepareStatement(
"insert into Media values (?, ?,?, ?,?, ?);");
System.out.print("Please choose a database(MedType or Media): ");
String db=input.next();
if(db.equalsIgnoreCase("MedType"))
{
System.out.print("Enter in ID: ");
String answer1 = input.next();
System.out.print("");
String answer2 = input.nextLine();
System.out.print("Enter in Description: ");
String answer3 = input.nextLine();
prep1.setString(1, answer1);//add values into cell
prep1.setString(2, answer3);
prep1.addBatch();//add the columns that have been entered
}
conn.setAutoCommit(false);
prep1.executeBatch();
prep2.executeBatch();
conn.setAutoCommit(true);
System.out.print("Please Enter Query(One or All): ");
String q=input.next();
ResultSet rs= stat.executeQuery("select * from MedType;");
if(q.equalsIgnoreCase("all")){
while (rs.next()) {
System.out.print("All ID = " + rs.getString("ID") + " ");
System.out.println("All Description = " + rs.getString("Description"));}
}
if(q.equalsIgnoreCase("one")){
System.out.print("Enter ID: ");
}
int idNum=input.nextInt();
ResultSet oneRs = stat.executeQuery("select * from MedType Where"+ (rs.getString("ID")+"="+idNum));
if(q.equalsIgnoreCase("one")){
while (oneRs.next()) {
System.out.print("ID = " + oneRs.getString("ID") + " ");
System.out.println("Description = " + oneRs.getString("Description"));
}
}
rs.close();
oneRs.close();
conn.close();
}
}
ResultSet oneRs = stat.executeQuery("select * from MedType Where"+
(rs.getString("ID")+"="+idNum));
This is where I'm having trouble. Creating a statement that says return something from the table if its id is equal to the user input. I get this error
Exception in thread "main" java.sql.SQLException: [SQLITE_ERROR] SQL error or missing database (near "=": syntax error)
In query you are trying to access single row by passing id.. In generally sql query we are using to access single row by passing some information. select * from MedType where id=3 this query will return you result set containing row or rows with id equals to 3.
so in your code your query should be select * from MedType where id="+idNum+" if in your db id column is int.
and keep this query in if block only i.e
if(q.equalsIgnoreCase("one"))
{
System.out.print("Enter ID: ");
int idNum=input.nextInt();
ResultSet oneRs = stat.executeQuery("select * from MedType Where id="+idNum+" ");
// if id column in db is int if it is string then use id='"+idNum+"'
while (oneRs.next())
{
System.out.print("ID = " + oneRs.getString("ID") + " ");
System.out.println("Description = " + oneRs.getString("Description"));
}
}
In your query:
select * from MedType Where"+ (rs.getString("ID")+"="+idNum
you seem to try to grab the ID from the first resultset where you return all tuples.
That won't work as in the where clause the ID won't be there (as there is no result right now without rs.next()). If there was a result then you potentially have something like 'where 3 = 3' (3 would be the result of the previously returned value. Have you tried simply to use:
select * from MedType Where ID = " + idNum
Hope that makes sense.