Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLServer Exception: Invalid column name

com.microsoft.sqlserver.jdbc.SQLServerException: Invalid column name 'IDPaciente'

I am getting this exception. This is my code:

    String query = "INSERT INTO Paciente('IDPaciente', 'NomePaciente', 'IdadePaciente', 'LocalidadePaciente') VALUES('"+IDTextField.getText()+"', '"+NomeTextField.getText()+"', '"+IdadeTextField.getText()+"', '"+LocalidadeTextField.getText()+"')";
    try
    {
        st = con.DatabaseConnection().createStatement();
        rs = st.executeQuery(query);
    }

I suspect the problem might be in the query itself.

I have searched a lot and couldn't find the solution to my problem. I have tried refreshing the cache, changing permissions within the schema, restarting sql server (I am using sql server management studio 2012), I am correctly connected to my database, and nothing seems to work.

What could I be doing wrong? Thank you!

like image 753
Gazelle Avatar asked Dec 03 '25 14:12

Gazelle


2 Answers

Remove quotes , try :

String query = "INSERT INTO Paciente(IDPaciente, NomePaciente, IdadePaciente, LocalidadePaciente) VALUES('"+IDTextField.getText()+"', '"+NomeTextField.getText()+"', '"+IdadeTextField.getText()+"', '"+LocalidadeTextField.getText()+"')";
try
{
    st = con.DatabaseConnection().createStatement();
    rs = st.executeQuery(query);
}

Remove also quotes for INT values.

like image 104
Ilyes Avatar answered Dec 06 '25 08:12

Ilyes


Your code is not secure, you can easily get Syntax error or SQL Injection I suggest to use PreparedStatement instead.

You have a problem in your Query, the columns should not be between '' so you can use this instead :

String query = "INSERT INTO Paciente(IDPaciente, NomePaciente, IdadePaciente, "
        + "LocalidadePaciente) VALUES(?, ?, ?, ?)";

try (PreparedStatement insert = con.prepareStatement(query)) {
    insert.setString(1, IDTextField.getText());
    insert.setString(2, NomeTextField.getText());
    insert.setString(3, IdadeTextField.getText());
    insert.setString(4, LocalidadeTextField.getText());

    insert.executeUpdate();
}

If one of your column is an int you have to use setInt, if date setDate, and so on.

like image 23
YCF_L Avatar answered Dec 06 '25 07:12

YCF_L