Inserting Error - sql

I'm trying to insert in postgresql db date, but when I'm inserting it, I'm getting this error:
Error occurred while INSERTING operation: org.postgresql.util.PSQLException: ERROR: column "text that i wrote" does not exist"
I don't understand what did I code wrong that, program tries to find column in values?
But when I try to output this table, it outputs without errors
WORKERDAO class
public static void insertWrk(String name, String post) throws SQLException, ClassNotFoundException {
//Declare a INSTERT statement
String updateStmt ="INSERT INTO worker(full_name,post)" +
"VALUES" +
"("+name+","+post+");";
//Execute INSTERT operation
try {
DBUtil.dbExecuteUpdate(updateStmt);
} catch (SQLException e) {
System.out.print("Error occurred while INSTERING Operation: " + e);
throw e;
}
}
DBUTIL class
public static void dbExecuteUpdate(String sqlStmt) throws SQLException, ClassNotFoundException {
//Declare statement as null
Statement stmt = null;
try {
//Connect to DB
dbConnect();
//Create Statement
stmt = conn.createStatement();
//Run executeUpdate operation with given sql statement
stmt.executeUpdate(sqlStmt);
} catch (SQLException e) {
System.out.println("Проблема в выполнение executeUpdate операции : " + e);
throw e;
} finally {
if (stmt != null) {
//Close statement
stmt.close();
}
//Close connection
dbDisconnect();
}
}
WorkerController Class
#FXML
private void insertWorker (ActionEvent actionEvent) throws SQLException, ClassNotFoundException {
try {
WorkerDAO.insertWrk(nameText.getText(),postCombo.getSelectionModel().getSelectedItem());
} catch (SQLException e) {
System.out.println("Problem occurred while inserting worker " + e);
throw e;
}
}

You need to put quotes around the data you're inserting:
String updateStmt ="INSERT INTO worker(full_name,post)" +
"VALUES" +
"("+name+","+post+");";
Should be:
String updateStmt ="INSERT INTO worker(full_name,post)" +
"VALUES" +
"('"+name+"',"'+post+'");";
Be aware that you're risking SQL Injection attacks using this method, see about using a parameterised insert. This site lists a bit more detail.

Related

Getting error in SQL while trying to delete records with JDBC

I am trying to write a program that deletes all data from the database (MariaDB) using JDBC but I'm getting this error:
Exception in thread "main" java.lang.RuntimeException: java.sql.SQLSyntaxErrorException: 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 '' at line 1
at com.iffi.AccountData.clearDatabase(AccountData.java:35)
at com.iffi.AccountData.main(AccountData.java:679)
Caused by: java.sql.SQLSyntaxErrorException: 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 '' at line 1
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:953)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1098)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1046)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeLargeUpdate(ClientPreparedStatement.java:1371)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdate(ClientPreparedStatement.java:1031)
at com.iffi.AccountData.clearDatabase(AccountData.java:32)
... 1 more
Here's my code:
public class AccountData {
/**
* Removes all records from all tables in the database.
*/
public static void clearDatabase() {
Connection conn = ConnectionPool.getConnection();
PreparedStatement ps = null;
List<String> tables = Arrays.asList("table1", "table2", "table3", "table4", "table5", "table6", "table7", "table8");
for (String table: tables) {
String query = "Delete from" + table + ";";
try {
ps = conn.prepareStatement(query);
ps.executeUpdate();
} catch (SQLException e) {
ConnectionPool.LOG.error("SQL Exception: ", e);
throw new RuntimeException(e);
}
}
try {
ps.close();
ConnectionPool.putConnection(conn);
} catch (SQLException e) {
ConnectionPool.LOG.error("SQL Exception: ", e);
throw new RuntimeException(e);
}
}
}
Any ideas on what I might be doing wrong?
Try adding a space after from in your query string

How to get the method name and line number in Exception in ASP Core 5

I want to get the method name and line number when an error occur, I am using Core 5.
try
{
//My code
}
catch (Exception ex)
{
_logger.LogError(ex, "Method Name / Line Number");
}
Update:
I found a Solution like this:
_logger.LogError(ex, "\n=> ex Error: " + ex + "\n=> Action Name: " + ex.TargetSite.ReflectedType.Name + "\n=> Error Message: " + ex.Message + "\n=> Line Number: " + ex.LineNumber());
A simple call to ToString() on exception will give you the complete information needed. For example when we run the following code:
public static void Main()
{
try
{
//my code
throw new ArgumentException();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
The output would be somewhat like:
System.ArgumentException: Value does not fall within the expected range.
at ConsoleApp.Program.Main() in C:\Users\USER\source\Playground\ConsoleApp1\Program.cs:line 20
where Main() is the method name and 20 is the line number.
To get the format as required in question we can write a wrapper around the exception and fetch the line number from it:
using System;
using System.Reflection;
namespace ConsoleApp
{
class Program
{
public static void Main()
{
try
{
//my code
throw new ArgumentException();
}
catch (Exception ex)
{
Console.WriteLine(MethodBase.GetCurrentMethod().Name + "/" + GetLineNumber(ex));
}
}
public static int GetLineNumber(Exception ex)
{
var lineNumber = 0;
const string lineSearch = ":line ";
var index = ex.StackTrace.LastIndexOf(lineSearch);
if (index != -1)
{
var lineNumberText = ex.StackTrace.Substring(index + lineSearch.Length);
if (int.TryParse(lineNumberText, out lineNumber))
{
}
}
return lineNumber;
}
}
}
Note: In the extract line method, we are fetching the top most exception. This comes in handy when we have a chain of exceptions in our stack trace.

Get INSERT string on JDBC

I’m trying to write a method to get the string from the SQL INSERT query to the DB, with an input array as the number of columns using JDBC:
public String methodtest(String ListofColumns)
{
String query = "INSERT INTO" + TableName + "(" + ListOfColumns + ")";
try
{
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
While (rs.next())
{
String result = rs.getString(query);
System.out.println("The SQL query is " + result);
}
}
catch (SQLException sqlEx)
{
e.printStackTrace();
}
finally
{
rs.close();
}
}
Can you see any mistake?
Thanks, Monkawee, for the advice.
You can use the following pattern:
public string methodtest(Array listofcolumns)
{
try{
<Connection string path>
<DB connection method>
<Query string>
<Execution>
<Reset Object>
}
catch(SQLException sqlEx){
// handle exception
}
catch(Exception ex){
// handle other exceptions if any
}
finally{
<Close connection and other resources like PreparedStatement>
}
}

ResultSet is getting closed on executing statement.execute(sql)

On executing the follwing code i am getting error java.sql.SQLException: ResultSet is closed
public class SavePoints {
public void extract(ResultSet rs)
{
int c;
try {
while(rs.next())
{
c = rs.getInt("id");
String d=rs.getString("name");
String e=rs.getString("city");
String f=rs.getString("state");
String g=rs.getString("country");
//Displaying values
System.out.println("ID is:"+c+"\tName is:"+d+"\tCity is:"+e+"\tState is:"+f+"\tCountry is:"+g);
}
} catch (SQLException e1) {
e1.printStackTrace();
}
}
public static void main(String[] args) {
SavePoints spobj=new SavePoints();
try {
Connection con=DriverManager.getConnection("jdbc:odbc:Divya", "SYSTEM", "tiger");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from publishers");
spobj.extract(rs);
//DatabaseMetaData databaseMetaData = con.getMetaData();
//System.out.println(databaseMetaData.getDriverMajorVersion());
//Savepoint sp=con.setSavepoint("Deleting Rows");
st.execute("delete from publishers where id=104");
//con.rollback(sp);
spobj.extract(rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
What is the error? I cannot find it. Please let me know. I am a newbie.. so please explain in simple terms. I am grateful for your help. Thanks :)
you have called spobj.extract(rs); twice ,
first time when this function executes resultset moves to last because you are using rs.next()..
to achieve this you have use scrollable resultset
Statement st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
and for next call of spobj.extract(rs); reverse the call of resultset by rs.previous()

SQL Server, JTDS causes java.sql.SQLException: Invalid state, the ResultSet object is closed

I am using Tomcat 7, Microsoft SQL Server 2008 RC2 and JTDS driver
I am actually using C3P0 as well to try and solve this problem, but it makes no difference at all. I was using Microsoft's driver but it caused me other problems (the requested operation is not supported on forward only result sets)
I get the following error, always at the same point. I have successfully run other queries before getting to this point:
java.sql.SQLException: Invalid state, the ResultSet object is closed.
at
net.sourceforge.jtds.jdbc.JtdsResultSet.checkOpen(JtdsResultSet.java:287)
at
net.sourceforge.jtds.jdbc.JtdsResultSet.findColumn(JtdsResultSet.java:943)
at
net.sourceforge.jtds.jdbc.JtdsResultSet.getInt(JtdsResultSet.java:968)
at
com.mchange.v2.c3p0.impl.NewProxyResultSet.getInt(NewProxyResultSet.java:2573)
at com.tt.web.WebPosition.createPosition(WebPosition.java:863)
The code is as follows:
public static List getListPositions(String query) {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
List list = null;
try { //execute the sql query and create the resultSet
con = DBConnection.getInstance().getConnection();
stmt = con.createStatement();
rs = stmt.executeQuery(query);
while(rs.next()) {
if(rs.isFirst()) {
list = new ArrayList();
}
WebPosition webPos = null;
webPos = new WebPosition(rs);
list.add(webPos);
}
} catch (java.sql.SQLException e) {
System.out.println("SQLException in getListPositions");
System.out.print(query);
Log.getInstance().write(query);
Log.getInstance().write(e.toString());
} catch (Exception ex) {
System.out.print(ex);
ex.printStackTrace();
Log.getInstance().write(ex.toString());
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
Log.getInstance().write(e.toString());
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
Log.getInstance().write(e.toString());
}
}
DBConnection.getInstance().returnConnection(con);
}
return list;
}
public WebPosition(ResultSet rs) {
createPosition( rs);
}
public void createPosition(ResultSet rs) {
try {
this.setCurrentDate4Excel(rs.getString("SYSDATE_4_EXCEL"));
this.setExerciseType(rs.getInt("EXERCISE_STYLE_CD"));
...
The code fails in between the above two lines.
I am at a loss to explain why the Result set would be closed in the middle of a function (i.e. it would retrieve rs.getString("SYSDATE_4_EXCEL") but then fail with the error posted at the line rs.getInt("EXERCISE_STYLE_CD"))
Does anyone have any ideas? I imagine that it is some kind of memory issue, and that the connection is automatically closed after a certain amount of data, but I am not sure how to fix this. I tried increasing the heapsize for the JVM.