How can I display data into my Jtextarea from my data base Mysql - mysql

I have problem when I try to display data(the result of a query) from my database mysql to my jTextarea, when I compile I have an error exception like:
SQL Exception: java.sql.SQLException: Can not issue SELECT via executeUpdate()
I have used a "select" query from my table where the name is the name written in my jTextFieldNom,this is my code, I hope that some one help me because I don't know how to resolve the problem, I 'm sure that my query is correct but I don't know where is the problem.
String pilote = "com.mysql.jdbc.Driver";
jComboBoxType.addItemListener(new ItemState());
jComboBoxMenaces.addItemListener(new ItemState());
try {
Class.forName(pilote);
Connection connexion = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root"," ");
Statement instruction = connexion.createStatement();
String a=jTextFieldNom.getText();
String SQL = "select description from table where nomcol="+a+";";
ResultSet rs = instruction.executeQuery(SQL);
instruction = connexion.createStatement();
int rowsEffected = instruction.executeUpdate(SQL);
jTextArea1.append(rs.getString("description"));
}
...... //bloc catch

This line is executing a Select statement which is throwing the error.
int rowsEffected = instruction.executeUpdate(SQL);
You don't need this line because you aren't updating your database.
Also change the append to setText
jTextArea1.setText(rs.getString("description"));
Try this:
String pilote = "com.mysql.jdbc.Driver";
jComboBoxType.addItemListener(new ItemState());
jComboBoxMenaces.addItemListener(new ItemState());
try {
Class.forName(pilote);
Connection connexion = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test","root"," ");
Statement instruction = connexion.createStatement();
String a=jTextFieldNom.getText();
String SQL = "select description from table where nomcol="+a+";";
ResultSet rs = instruction.executeQuery(SQL);
jTextArea1.setText(rs.getString("description"));
}

Related

MySQL workbench returns stored procedure with multiple rows, but from Java code, only one row is returned

It is MYSQL, and the same stored procedure call in Workbench works fine, but from Java code, it always only return one row.
String sql = "{ CALL getList(?, ?, ?) }";
CallableStatement cs = conn.prepareCall(sql);
cs.setLong(1, key);
cs.setString(2, id);
cs.setInt(3, java.sql.Types.INTEGER);
ResultSet rs = cs.executeQuery();
rtn = cs.getInt(3); // this return as 1
while (rs.next()) {
String name = rs.getString("name");
String age= rs.getString("age");
//.....
}
from this while loop, always and only return one row, it is very strange, spend hours, no clue yet, please advice what may be wrong, the hint is that the MYSQL is old version 5.3, and Java is old version JDK 1.6.
Anybody have experience to deal with it, please advice, thanks.
In addition to what you have, you need to also implement the add() method. Try this:
String sql = "{ CALL getList(?, ?, ?) }";
CallableStatement cs = conn.prepareCall(sql);
cs.setLong(1, key);
cs.setString(2, id);
cs.setInt(3, java.sql.Types.INTEGER);
ResultSet rs = cs.executeQuery();
rtn = cs.getInt(3);
while(rs.next()) {
String name = add(rs.getString("name"));
String age= add(rs.getString("age"));
}

Java FXML - NetBeans - Delete from Table - MySQL

I get the following error when I attempt to delete a row from TableView:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '[value: 3]' at line 1
What I want: Once a row from TableView is selected, I want to delete it from database.
#FXML
void delete(ActionEvent event) {
try {
int pos;
pos = (int) tabelCustomers.getSelectionModel().getSelectedIndex();
Customers c;
c = tabelCustomers.getItems().get(pos);
SimpleIntegerProperty idc = c.idc;
String query;
query = "DELETE FROM customers WHERE customers.idc = " + idc;
try (Statement stm = cnx.createStatement()) {
stm.executeUpdate(query);
}
} catch (SQLException ex) {
Logger.getLogger(CustomersTableController.class.getName()).log(Level.SEVERE,
null, ex);
}
}
What am I missing? I have tried a lot of possible solutions, nothing works.
Basically, when a user clicks on the row in a table and then clicks on the "remove" button, that row should be deleted from table and DB.
Thanks in advance.
SimpleIntegerProperty idc = c.idc;
String query = "DELETE FROM customers WHERE customers.idc = " + idc;
When an Object (that is not a String) is used in string concatenation it is automatically converted into a String by calling toString() on it. The string representation of SimpleIntegerProperty is not simply its value, which means your query ends up looking something like:
DELETE FROM customers WHERE customers.idc = IntegerProperty [bean: <some_instance>, name: idc, value: 42]
Which is obviously not valid SQL. You need to extract the value of the property and use that as part of the query. However, you should not use string concatenation when creating SQL queries in the first place. You should instead be using a PreparedStatement with parameters. For example:
String query = "DELETE FROM customers WHERE customers.idc = ?";
try (PreparedStatement ps = cnx.prepareStatement(query)) {
ps.setInt(1, idc.get());
ps.executeUpdate();
}

How I can get the correct date of my Mysql query without the query itself subtracting one day to date

My problem is that in a table of my database with 7 columns, I have a column of date type, called "Fecnac". Through MYSQLworkbrench, I execute a simple query:
"SELECT * FROM tblAsegurados ORDER BY Name,Nss"
As a result of this query, the information of my columns or fields of the table is displayed, the table contains a column named "Fecnac" that shows the correct date, for example "2018-12-31".
MYSQLworkbrench Result image
However, I developed an application in intelliJ IDEA to execute the same query, and the query "by itself" returns the date with one day less, that is, it shows "2018-12-30". And so it does with all the dates found in the "Fecnac" column of the "tblAsegurados" table in my database.
public ArrayList<Asegurados> getAseguradosList(){
ArrayList<Asegurados> aseguradosList = new ArrayList<Asegurados>();
Connection connection = getConnection();
var query = "select * from tblAsegurados order by Nombre,Nss";
Statement st;
ResultSet rs;
try{
st = connection.createStatement();
rs = st.executeQuery(query);
Asegurados asegurado;
while(rs.next()){
asegurado = new Asegurados(
rs.getString("Nss"),
rs.getString("Nombre"),
rs.getString("Curp"),
rs.getBoolean("Esposa"),
rs.getInt("Semcot"),
rs.getInt("Hijos"),
rs.getDate("Fecnac"));
aseguradosList.add(asegurado);
System.out.println(asegurado.getFecnac());
System.out.println(rs.getDate("Fecnac"));
System.out.println(rs.getDate(7));
}
} catch (Exception e){
e.printStackTrace();
}
return aseguradosList;
}
The class "Asegurados" has an attribute of type "java.sql.date" defined, to receive "rs.getdate (Fecnac).
For i be sure of the values ​​returned by the query, in my code you can see that I made a "System.out.println" for each field date, and in all three I get the same value from the date with one day less.
Could someone help me know what happens?
Console debug IntelliJ Idea image
I already found the solution. In a part of my code, the parameter of the time zone had it defined as: serverTimezone = UTC
public static Connection getMySQLConnection() throws Exception {
String driver = "com.mysql.cj.jdbc.Driver";
String url = "jdbc:mysql://localhost/imss"+
"?useUnicode=true&useJDBCCompliantTimezoneShift=true"+
"&useLegacyDatetimeCode=false&serverTimezone=America/Mexico_City"+
"&verifyServerCertificate=false"+
"&useSSL=true"+
"&requireSSL=true";
String username = "root";
String password = "juan1980";
Class.forName(driver);
return DriverManager.getConnection(url, username, password);
}
I set it to: serverTimezone = america / Mexico_City, which is the zone that corresponds to me, and ready! the date is displayed correctly.

SQL WHERE LIKE clause in JSF managed bean

Hi i have this managed bean where it makes MySQL queries, the problem here is the SQL statement makes a '=' condition instead of 'LIKE'
Here is the code in my managed bean.
Connection con = ds.getConnection();
try{
if (con == null) {
throw new SQLException("Can't get database connection");
}
}
finally {
PreparedStatement ps = con.prepareStatement(
"SELECT * FROM Clients WHERE Machine LIKE '53'");
//get customer data from database
ResultSet result = ps.executeQuery();
con.close();
List list;
list = new ArrayList();
while (result.next()) {
Customer cust = new Customer();
cust.setMachine(result.getLong("Machine"));
cust.setCompany(result.getString("Company"));
cust.setContact(result.getString("Contact"));
cust.setPhone(result.getLong("Phone"));
cust.setEmail(result.getString("Email"));
//store all data into a List
list.add(cust);
}
return list;
Here the SELECT command does not pull all the numbers in 'Machine' column which is like 53, but if i enter a whole value, such as the complete number (53544) in place of 53 then the result is pulled up. I am confused !!
Also if i replace the above select statement with SELECT * FROM Clients the entire database is stored in list. Any ideas ?
Use wildcards:
Like '%53%'
...means everything that contains '53'.
Like '%53' - it ends with 53
LIKE '53%' - it starts with 53
You can also use _ if You want to replace a single character.
You can find a descriptipn HERE
You sql query should be
"SELECT * FROM Clients WHERE Machine LIKE '%53%'

ADODB Command failing Execute with parameterised SQL query

I have the following JScript code:
var conn = new ActiveXObject ("ADODB.Connection");
conn.Open("Driver={MySQL ODBC 5.1 Driver};Server=localhost;Database=blah_blah_blah;User=foo;Password=bar;");
var cmd = new ActiveXObject("ADODB.Command");
cmd.ActiveConnection = conn;
var strSQL = "SELECT id FROM tbl_info WHERE title LIKE :search ORDER BY id";
var search = "test";
try{
cmd.CommandText = strSQL;
var param = cmd.CreateParameter(':search', 200, 1, 100, search);
cmd.Parameters.Append(param);
var rs = cmd.Execute();
}
catch (ex) {
Application.Alert("Error retrieving id information from database.");
}
I've verified (by printing them) that the Connection object is set to be the Command's ActiveConnection, the parameter object has the correct value and the Command object has the correct SQL query as its CommandText. I also inserted an alert statement after each line in the try block to see where the error was occuring - it's fine after cmd.Parameters.Append but the exception gets thrown upon running the Execute statement.
I've tried displaying the actual exception but it's just a generic 'Object error' message.
The query executes fine and returns the correct result set when I just execute the SQL query (without the parameter) straight through the Connection object, but seems to fail when I use a parameterised query with the Command object.
As far as I can see all settings and properties of the Command and Connection objects are correct but for whatever reason it's throwing an exception.
Any help with this would be much appreciated.
With ODBC and ADO, generally speaking, a question mark ? is used as the placeholder for parameters. Parameters are bound in the order they are appended to the Parameters collection to the placeholders in the command. In your example, replace strSQL with:
var strSQL = "SELECT id FROM tbl_info WHERE title LIKE ? ORDER BY id";
You can still name the parameter that you create, but the only purpose it would serve is to be able to reference it by name later (e.g., with cmd.Parameters.Item(":search")).