"Column Count doesn't match value count at row 1" E - java

I've encountered an error and I'm not able to figure out my mistake. I've done my research and haven't found an appropriate answer for my question.
This is my code:
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {
String CN, CNo, MN, NT, SNo, VIP, T, D;
CN = TF1.getText();
CNo = TF2.getText();
MN = TF3.getText();
NT = TF4.getText();
SNo = TF5.getText();
VIP = TF6.getText();
T = TF7.getText();
D = TF8.getText();
try
{
Class.forName("java.sql.DriverManager");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/devika", "root", "rockgirl12");
Statement stmt = (Statement) con.createStatement();
String query = "INSERT INTO Maintenance VALUES ('"+CN+"',"+CNo+",'"+MN+"',"+NT+",'"+SNo+"','"+VIP+"','"+T+"','"+D+"');";
stmt.executeUpdate(query);
JOptionPane.showMessageDialog(this, "Record added succesfully!");
}
catch(Exception e)
{
JOptionPane.showMessageDialog(this, e.getMessage());
}
}
What I'm trying to do here is I'm adding data to my SQL database through a form I designed in Java Netbeans. I've attached the form I've created here.
My Form
Help would be greatly appreciated :)

Exactly what the error says. The number of columns and the fields in valules do not match. This sort of insert without specifing the column names isn't the best practice by any stretch. You should do
String query = "INSERT INTO Maintenance(col1, col2, col3, col4,..) VALUES ('"+CN+"',"+CNo+",'"+MN+"',"+NT+",'"+SNo+"','"+VIP+"','"+T+"','"+D+"');";
In fact, you shouldn't be doing this sort of string concatenation either. It's far better to use prepared statements. The current approach does not ensure that the data is properly escaped before being saved.

Related

Parameter index out of range (1 > number of parameters, which is 0) error

I am trying to use like operator to search database data and display in a jTable but I keep getting
the Parameter index out of range (1 > number of parameters, which is
0).
This is my code below.
private void jButton_searchActionPerformed(java.awt.event.ActionEvent evt) {
//button captures data from textbox and displays on table
PreparedStatement ps;
ResultSet rs;
String Search = jTextField_search.getText();
try {
String query = "SELECT * FROM books WHERE Title like ' %`?`%' " ;
ps = conn.getConnection().prepareStatement(query);
ps.setString(1, Search);
rs = ps.executeQuery();
jTable2.setModel(DbUtils.resultSetToTableModel(rs));
}
catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
I suggest binding the wildcard expression as a string to a standalone ? placeholder in your prepared statement:
String Search = jTextField_search.getText();
try {
String query = "SELECT * FROM books WHERE Title LIKE ?";
ps = conn.getConnection().prepareStatement(query);
ps.setString(1, "%" + Search + "%");
rs = ps.executeQuery();
jTable2.setModel(DbUtils.resultSetToTableModel(rs));
}
catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
}
I don't really know why you are using backticks in your LIKE expression. Backticks are used by MySQL (and perhaps a few other) databases to escape objects, such as column and table names. It probably doesn't make sense for your query.
To explain your current error, in MySQL placing ? surrounded by backticks will escape the binding placeholder and instead make it a literal ?. This could explain the complaint that you have no parameters.

SQL Query In Java + Oracle

I'm really struggling to get this SQL into my head while using java.
My problem is: I want to use a variable in my sql Query, and i cant seem to get it working, it catches the correct value(i'm showing it on a label), But it doesnt show any records, yet, if i replace the variable for a '5', it shows me the correct record...
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = MySqlConnect.ConnectDb();
int idaca = Integer.parseInt(idhist.getText());
String query1 = "SELECT t.nome, h.Valor_Atual, h.Valor_Antigo, a.nome
FROM Tecnologias t, Historico h, Academista a
WHERE h.Id_Academista = a.Id_Academista AND a.Id_Academista = "+idaca+" AND h.Id_Tecnologia = t.Id_Tecnologia
AND (h.Valor_Atual || h.Valor_Antigo || t.nome) LIKE '%" + ValToSearch + "%'";
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(query1);
historico history;
while (rs.next()) {
history = new historico(rs.getString("Nome"), rs.getInt("Valor_Antigo"),
rs.getInt("Valor_Atual"), rs.getString("Nome"));
historicoList.add(history);
} //END WHILE
} //END TRY
catch (Exception e) {
JOptionPane.showInputDialog(null, e);
}//END CATCH
Thats my code so far... The ValToSearch is working fine, tho...
Thank you in advance! Cheers
Put an space before AND h.Id_Tecnologia. That should solve your problem.
You are not afraid that in ValToSearch you get something like ' OR 1 IN (DELETE * FROM Tecnologias )?
Use parametr escaping or better some query builder

How sql works and why this result is returned?

Hi I'm using preparedStatement in Java to execute query in DB.
The table:
When it comes to update, delete and insert it's all fine, however when it comes to select( ex. I've done "SELECT ?,?,?,?,? from person" and set strings afterwards) and the following result is returned:
I'm assuming that because it's the strings that are replacing ? so it did not come out as expected:(please correct me if it's wrong)
Expected sql: "SELECT no,name,tel,birthday,address FROM person"
Actual sql: "SELECT \"no\",\"name\",\"birthday\",\"address\" FROM person"
I've tested the second one in in Navicat:
I'd like to understand that why executing this query statement would return a result like this?
If it would help here's Java code:
// Data Assist Object
public class DAO {
static String jdbcurl;
static String username;
static String password;
static{
try {
Class.forName("com.mysql.jdbc.Driver");
ResourceBundle rb = ResourceBundle.getBundle("db");
jdbcurl = rb.getString("jdbcurl");
username = rb.getString("username");
password = rb.getString("password");
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
}
// for insert, delete and update
public int modify(String sql, String[] args){
int x=0;
try(Connection con = DriverManager.getConnection( jdbcurl,username ,password);
PreparedStatement ps = con.prepareStatement(sql);){
for (int i = 0; i < args.length; i++) {
ps.setString(i+1, args[i]);
}
x =ps.executeUpdate();
System.out.println(x);
}catch(SQLException e){
e.printStackTrace();
}
return x;
}
// for select
public List<Map<String,String>> query(String sql, String[] params){
List<Map<String,String>> resList = new ArrayList<>();
try(Connection con = DriverManager.getConnection( jdbcurl,username ,password);
PreparedStatement ps = con.prepareStatement(sql);){
for (int i = 0; i < params.length; i++) {
ps.setString(i+1, params[i]);
}
try(ResultSet res =ps.executeQuery();){
ResultSetMetaData mdata = res.getMetaData();
int num = mdata.getColumnCount();
while(res.next()){
HashMap<String,String> data = new HashMap<>();
for (int i = 1; i <= num; i++) {
String result = res.getString(i);
String columnName = mdata.getColumnName(i);
data.put(columnName,result);
}
resList.add(data);
}
}
}catch(Exception e){
e.printStackTrace();
}
return resList;
}
public static void main(String[] args) throws SQLException {
DAO dao = new DAO();
String sql = "insert into person(name,tel,birthday,address) values(?,?,?,?)";
sql = "select ?,?,?,?,? from person";
List<Map<String,String>> res = dao.query(sql, new String[]{"no","name","tel","birthday","address"});
for(Map m:res){
System.out.print("no: "+m.get("no")+",");
System.out.print("name: "+m.get("name")+",");
System.out.print("tel: "+m.get("tel")+",");
System.out.print("birthday: "+m.get("birthday")+",");
System.out.println("address: "+m.get("address"));
}
}
}
Thanks for any help.
SQL basically works on a show me these columns where this criteria is true basis.
In the statement:
"SELECT \"no\",\"name\",\"birthday\",\"address\" FROM person"
You're getting
SELECT "no", "name", "birthday", "address" FROM person
when it actually hits the database. The "" operator creates a string in SQL. In plain English, that means that you're telling the database to return that specified set of strings for each row in person where the criteria you listed is met.
Since you didn't list a where clause, all rows are true by default so you get one row of strings for every single row in the person table. The first query is the same thing, but instead of directly passing the strings, you're adding them in as bind variables.
If you actually want to see the values in the table, write the query without the "'s
SELECT no, name, birthday, address FROM person
Unless otherwise specified, bind functions generally pass the value as a string. Which is why the query behaved the way it did. I don't recommend using bind variables in the select clause. That's a strange practice.
Edit:
As Adrian pointed out in the comments, " denotes columns in SQL. My apologies for not catching that. I assume that you meant to use the ' operator which actually denotes strings.
If not, something else is going on here entirely.
For the select you use the question marks in the WHERE clause, not where you list the fields you need as output.
Replace
sql = "select ?,?,?,?,? from person";
with
sql = "select no,name,tel,birthday,address from person";
For this particular query there is no binding to do. It will retrieve all the records from the table.

difficult time inserting data with textfield( jdbc swing)

My insert into is giving me issues.
Im pretty sure the Jtextfield is the problem.
If anyone can give me a nudge in the right direction I would greatly appreciate it.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:#//localhost:1521/xe";
Connection conn = DriverManager.getConnection(url, "system", "oracle");
conn.setAutoCommit(false);
String query1 = "INSERT INTO WIN(NAME) VALUES('"+nameTextField.getSelectedText()+"')";
Statement stm = conn.createStatement();
stm.execute(query1);
JOptionPane.showMessageDialog(null, "Record Added Succesfully.", "Record Added",
JOptionPane.INFORMATION_MESSAGE);
} catch (Exception e) {
System.out.println(e);
}
}
nameTextField.getSelectedText()
I'm guessing that should be
nameTextField.getText()
Also, use a PreparedStatement for the SQL. You will less likely to make SQL syntax errors. Check out: geting data from multiple table when selecting a row then clicking a button for a basic example.
Im pretty sure the Jtextfield is the problem.
Well, learn how to do some basic debugging instead of guessing.
String query1 = "INSERT INTO WIN(NAME) VALUES('"+nameTextField.getSelectedText()+"')";
The above code can be written like:
String name = textField.getSelectedText();
// now you can verify the value of the name
System.out.println(name);
String query1 = "INSERT INTO WIN(NAME) VALUES('"+ name +"')";
// verify SQL syntax
System.out.println( query1);
Of course my first suggestion to use the PreparedStatement is easier, but learn how to display the value of variables when you do debugging.

Populating JTable with data in SQL database

This one is related to THIS question which I asked before, this one kinda solve my problem but another problem came up and I'm asking myself 'why is that?'.
here is the codes (BTW I used r2xml.jar in this project) :
private void search() throws Exception{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:*****";
String user = "*****";
String pass = "*****";
Connection conn = DriverManager.getConnection(url, user, pass);
PreparedStatement ps;
ResultSet rs;
String custname = "SELECT pIDNo AS 'Patient ID',pLName AS 'Last Name', pFName AS 'First Name',pMI AS 'M.I.',pSex AS 'Sex',pStatus AS 'Status', pTelNo AS 'Contact No.', pDocID AS 'Doctor ID', pAddr AS 'St. No.',pStreet AS 'St. Name',pBarangay AS 'Barangay',pCity AS 'City', pProvince AS 'Province', pLNameKIN AS 'Last Name',pFNameKIN AS 'First Name',pMIKIN AS 'M.I.',pRelationKIN AS 'Relation',pTotalDue AS 'Total Due' FROM dbo.Patients where pIDNo LIKE '" + "%'";
ps = conn.prepareStatement(custname);
rs = ps.executeQuery();
tblPatient.setModel(DbUtils.resultSetToTableModel(rs));
}
Now here is my concern on the link that I gave, I can't make the TotalDue column data display on my JTable I dunno if it's because of the DATA TYPE that it has which is MONEY. but after using the codes above I manage to display it, but the problem now is that the other columns is now missing, non of them display on my column except TotalDue. Is there any explanation on that? is there a solution? I used this r2xml.jar before and it works fine but now I don't know what is the problem or am I missing something?
Then better go on the hard way, and this works as a charm.
DefaultTableModel tbl = (DefaultTableModel) tblPatient.getModel();
ResultSetMetaData rm = rs.getMetaData(); // this line is useless if you know the column count. (I was too lazy to count :P )
int size = rm.getColumnCount();
while(rs.next()){
Object[] obj = new Object[size];
for(int i=0;i<size;i++){
obj[i] = rs.getObject(i+1);
}
tbl.addRow(obj);
}

Categories

Resources