I'm trying to write a class that will accept two strings and an int (username and password and score) from a quizgame, which eventually will come from a GUI, at the minute I'm just passing them through from the main, and pass them into a database to be inserted.
I have the JConnector jar file added and am working in Eclipse.
Here is my code
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
//public
class DbConnect {
private java.sql.Connection con;
private java.sql.Statement st;
private ResultSet rs;
public DbConnect() {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3307/nostalgic", "root", "usbw");
st = con.createStatement();
} catch (Exception ex) {
System.out.println("Error is " + ex);
}
}
public void setData(String n, String p, int x) {
try {
String query = "select * from nostalgic";
String query1 = "INSERT INTO nostalgic values (n,p,x)";
PreparedStatement statement3 = con.prepareStatement(query1);
statement3.executeUpdate();
rs = st.executeQuery(query);
System.out.println("records from database");
while (rs.next()) {
String name1 = rs.getString("name");
String pw = rs.getString("password");
int score = rs.getInt("score");
System.out.println("Name : " + name1);
System.out.println("Password : " + pw);
System.out.println("Score : " + score);
}
} catch (Exception ex) {
System.out.println(ex);
}
}
}
The error I get is
Unknown column 'n' in 'field list'
I can directly put a string in like 'john' but that is no use to me in this situation.
Instead of INSERT INTO nostalgic values (n,p,x) you should have
INSERT INTO nostalgic values (?,?,?) and then:
PreparedStatement statement3 = con.prepareStatement(query1);
statement3.setString(1,n);
statement3.setString(2,p);
statement3.setString(3,x);
statement3.executeUpdate();
in
String query1 = "INSERT INTO nostalgic values (n,p,x)";
n,p,x are not being replaced with the values, they are just being considered as some char that's why you get this error
Edit : before statement3.executeUpdate();
String query1 = "INSERT INTO nostalgic values (?,?,?)";
PreparedStatement statement3 = con.prepareStatement(query1);
statement3.setString(1,n);
statement3.setString(2,p);
statement3.setInt(3,x);
Update: you may wonder why Unknown column 'n' in 'field list'?
Because as insert query in sql can have this structure
INSERT INTO table (col1,col2,...) values (`val1`,`val2`,....)
but then values need to be inside `` if hard coded so if there is no `` sign they are considered as column name.
Mick,
the problem is that you don't pass actual parameters to your query when doing statement3.executeUpdate();. Check this link to see how to do it: http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html.
You cannot do it like that try this:
Class.forName("com.mysql.jdbc.Driver");
try (Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3307/nostalgic","root","usbw") {
PreparedStatement pr = null;
String query = "INSERT INTO nostalgic VALUES ((?), (?), (?))";
pr = con.prepareStatement(query);
pr.setString(1, n);
pr.setString(2, p);
pr.setString(3, x);
int status = pr.executeUpdate();
}catch (ClassNotFoundException | SQLException e) {
System.out.println(e.getMessage());
}
There are some mistakes in your code...
Correct imports
Insert statement
Your code will be like that:
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Connection;
import java.jdbc.Statement;
// you imported sql innecessary statements...
//public
class DbConnect {
// dont need complete path, you already imported it
private Connection con;
private Statement st;
private ResultSet rs;
public DbConnect() {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3307/nostalgic", "root", "usbw");
st = con.createStatement();
} catch (Exception ex) {
System.out.println("Error is " + ex);
}
}
public void setData(String n, String p, int x) {
try {
String query = "select * from nostalgic";
String query1 = "INSERT INTO nostalgic values (?,?,?)";
// no need to define vars here,
// just number of places to be inserted here ----^
PreparedStatement statement = con.prepareStatement(query1);
// prepare statement
statement = con.prepareStatement(query);
// insert the variables in places you prepared before
// and matching the types you need!!!
statement.setString(1,n);
statement.setString(2,p);
statement.setInt(3,x);
rs = st.executeQuery(query);
System.out.println("records from database");
while (rs.next()) {
String name1 = rs.getString("name");
String pw = rs.getString("password");
int score = rs.getInt("score");
System.out.println("Name : " + name1);
System.out.println("Password : " + pw);
System.out.println("Score : " + score);
}
} catch (Exception ex) {
System.out.println(ex);
}
}
}
Related
I have a complex directory system with millions of xml files which i need to retrieve to an XMLType column in Oracle 18c. I'm working with a java method that is executed by a procedure to re-load this files on this particular table. Since a lot of the of the java libraries were deprecated i'm out of options to solve this issue. The way I had finded to workaround was a tempory table with a CLOB column where I can insert the content from the files and than inside oracle I insert those in the original table using a XMLType(clobVariable). BUT, it doesnt work on files larger then 20k characters.
If anyone can help me I'm more than glad to give more information.
(I'm from Brazil and maybe I didn't made myself clear on the explanation btw)
public static void inserirXml() throws Exception{
try {
int num_id_nfe;
String dirArquivo = "";
String query;
String queryUpdate;
String reCheck, insert;
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection("jdbc:default:connection:");
conn.setAutoCommit(false);
query = "SELECT ID_NFE, DSC_CAMINHO_XML FROM DFE_NFE_CAMINHO_XML WHERE FLG_CARREGADO = 0 AND ROWNUM <= 1000";
Statement stmt = conn.createStatement();
Statement stmt2 = conn.createStatement();
Statement stmt3 = conn.createStatement();
Statement stmt4 = conn.createStatement();
stmt.executeQuery(query);
ResultSet rset = stmt.getResultSet();
while(rset.next() == true) {
try {
num_id_nfe = rset.getInt(1);
dirArquivo = rset.getString(2);
byte[] bytes = Files.readAllBytes(Paths.get(dirArquivo));
String xmlString = new String(bytes, "utf-8");
String insertQuery = "INSERT INTO DFE_NFE_REP_XML_TMP (ID_NFE, XMLCLOB) VALUES(?,?)";
PreparedStatement pstmt = conn.prepareStatement(insertQuery);
xmlString = xmlString.substring(1);
pstmt.setInt(1, num_id_nfe);
pstmt.setNString(2, xmlString);
pstmt.execute();
pstmt.close();
queryUpdate = "UPDATE DFE_NFE_CAMINHO_XML SET FLG_CARREGADO = 1 WHERE ID_NFE = " + num_id_nfe + " \n";
stmt2.executeQuery(queryUpdate);
}catch(SQLException e) {
System.err.println(e.getMessage()+" loop");
stmt2.close();
throw e;
}
}
insert = "INSERT INTO DFE_NFE_REP_XML (ID_NFE, CONTEUDO) SELECT ID_NFE, XMLType(XMLCLOB) FROM DFE_NFE_REP_XML_TMP";
stmt4.executeUpdate(insert);
reCheck = "UPDATE DFE_NFE_CAMINHO_XML SET FLG_CARREGADO = 0 WHERE id_nfe not in (select id_nfe from dfe_nfe_rep_xml) and flg_carregado = 1";
stmt3.executeQuery(reCheck);
conn.commit();
rset.close();
stmt.close();
stmt2.close();
stmt3.close();
stmt4.close();
conn.close();
} catch (SQLException x) {
System.err.println(x.getMessage()+" geral");
}catch (ClassNotFoundException y) {
throw y;
}catch(Exception z) {
throw z;
}
}
I am trying to query data from the database using JDBC, but I cant get the SELECT SUM() to work on the third switch case. All the other cases and SELECT amount on the third case work just fine, but when I try to use SELECT SUM(amount) it gives the error "no such column: 'amount'".
Here is my code:
package net.sqlitetutorial;
import java.util.Scanner;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SQLMain {
private Connection connect() {
String url = "jdbc:sqlite:C://sqlite/db/test.db";
Connection conn = null;
try {
conn = DriverManager.getConnection(url);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return conn;
}
public void selectAll(){
String sql = "SELECT name, amount FROM names ORDER BY amount desc";
try (Connection conn = this.connect();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)){
while (rs.next()) {
System.out.println(rs.getString("name") + "\t" +
rs.getInt("amount"));
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
public void selectNames(){
String sql = "SELECT name FROM names ORDER BY name";
try (Connection conn = this.connect();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)){
while (rs.next()) {
System.out.println(rs.getString("name"));
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
public void selectAmount(){
String sql = "SELECT sum(amount) FROM names";
try (Connection conn = this.connect();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)){
while (rs.next()) {
System.out.println(rs.getInt("amount"));
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
public static void main(String[] args) {
SQLMain app = new SQLMain();
int number;
Scanner console = new Scanner(System.in);
System.out.println("Choose one by entering a number:\n 1. List all ordered by most popular name first\n 2. List names in alphabetical order");
number = console.nextInt();
switch (number)
{
case 1 :
app.selectAll();
break;
case 2 :
app.selectNames();
break;
case 3 :
app.selectAmount();
break;
default:
System.out.println("Invalid input");
}
}
}
This is the error it gives out:
no such column: 'amount'
In this statement:
SELECT sum(amount) FROM names
there is no column returned by the name amount.
You must set an alias to the column returned:
SELECT sum(amount) AS amount FROM names
Or, without aliasing the column, you could get its value by its index which is 1:
System.out.println(rs.getInt(1));
This is because the result contains SUM(amount) and not the column amount.
You can for instance fix this by changing the query to
"SELECT sum(amount) AS amount FROM names"
or getting the result by index
rs.getInt(1);
Your query really doesn't have a an amount column in it - it has sum(amount). You could use an alias as forpas' answer suggests, or just the index (remember - column indexes in JDBC are one-based):
while (rs.next()) {
System.out.println(rs.getInt(1));
}
I am trying fetch data based on a condition on committee column using jdbc.Using Statement it produces the desired result but using PreparedStatement it does not.I cannot figure out what has gone wrong.Kindly help.Here is both the programs one using Statement and the other one using PreparedStatement and my table structure as well
import java.sql.*;
class SelectPrepared {
public static void main(String args[]) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe", "abcd","abcd");
String sql = "select * from tatuserinfo where committee = 'GENERAL'";
Statement stmt = con.createStatement();
// stmt.setString(1,"GENERAL");//1 specifies the first parameter in the query
ResultSet myRs = stmt.executeQuery(sql);
while (myRs.next()) {
System.out.println(myRs.getString(1) + myRs.getString(2) + myRs.getString(3) + myRs.getString(4)
+ myRs.getString(5) + myRs.getString(6) + myRs.getString(7) + myRs.getString(8));
}
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
import java.sql.*;
class SelectPreparedOne {
public static void main(String args[]) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
String s = "GENERAL";
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe", "abcd","abcd");
String sql = "select * from tatuserinfo where committee = ?";
PreparedStatement stmt = con.prepareStatement(sql);
stmt.setString(1, s);// 1 specifies the first parameter in the query
ResultSet myRs = stmt.executeQuery();
while (myRs.next()) {
System.out.println(myRs.getString(1) + myRs.getString(2) + myRs.getString(3) + myRs.getString(4)
+ myRs.getString(5) + myRs.getString(6) + myRs.getString(7) + myRs.getString(8));
}
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
Table structure
USERNAME VARCHAR2(40)
PASSWORD VARCHAR2(40)
ROLE VARCHAR2(40)
NAME VARCHAR2(40)
DESIGNATION VARCHAR2(40)
DEPARTMENT VARCHAR2(40)
EMAILID VARCHAR2(40)
COMMITTEE CHAR(15)
TL/DR: don't use char use varchar2
CHAR(15) gets blank padded to 15 characters, so the column contains the value 'GENERAL ' and that's not equal to the supplied value of 'GENERAL'
The correct fix is to change the column to VARCHAR2(15)
An intermediate ugly workaround (until you fix the column definition) is to use trim:
where trim(committee) = ?;
When created random email and store in mysql database its working fine then i try to print that random email but i can't. Anyone help me where can i edit my code?
Without ResultSet rs=statement.executeQuery("select * from user_data"); and
System.out.println(rs.getString(1)); its working fine
note:- someone please edit my grammar
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Random;
public class new_test {
public static void main(String[] args) {
ArrayList<String>objectsToStores = new ArrayList<>();
Random rad = new Random();
for (int j=1; j<=3; j++ )
{
objectsToStores.add("usename"+rad.nextInt()+"#gmail.com");
}
try {
Class.forName("com.mysql.jdbc.Driver") ;
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useSSL=false", "root", "");
connection.setAutoCommit(false);
Statement statement = connection.createStatement();
ResultSet rs=statement.executeQuery("select * from user_data");
for (String x : objectsToStores ) {
statement.executeUpdate("INSERT INTO USER_DATA (email) VALUES ('" +x +"')");
}
while(rs.next())
System.out.println(rs.getString(1));
connection.commit();
statement.close();
connection.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
The problem was the order that you were using for executing queries on the db
I just moved down the line
ResultSet rs = statement.executeQuery("select * from user_data");
after
statement.executeUpdate("INSERT INTO USER_DATA (email) VALUES ('" + x + "')");
This solve the problem because when you execute the UPDATE (second query) the ResultSet from the SELECT
get closed by the statement so you can't iterate it, and give you an error
try {
// This is not needed anymore with the new driver
//Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useSSL=false", "root", "");
connection.setAutoCommit(false);
Statement statement = connection.createStatement();
for (String x : objectsToStores) {
statement.executeUpdate("INSERT INTO USER_DATA (email) VALUES ('" + x + "')");
}
// I just moved this line down
ResultSet rs = statement.executeQuery("select * from user_data");
while (rs.next())
System.out.println(rs.getString(1));
connection.commit();
statement.close();
connection.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
I find that the control never seems to go in if block that starts from "if(sqlquery.equals("1"))" when it actually returns to be true. What could be the reason to it and how should ! modify it ?My program code is :
//package searchbook;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.util.*;
public class SearchBook extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException{
response.setContentType("text/html");
HttpSession session = request.getSession(true);
List booklist=new ArrayList();
Connection con = null;
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\users\\ppreeti\\executive_db.accdb";
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
String user = "";
String pass = "";
String category="";
category=request.getParameter("input");
String sqlquery="select Index1.link_id "
+ "FROM Index1 "
+ " WHERE Index1.index_name LIKE '%"+category+"%' ";
try
{
Class.forName(driver);
con = DriverManager.getConnection(url, user, pass);
try{
Statement st = con.createStatement();
System.out.println("Connection created 1");
ResultSet rs = st.executeQuery(sqlquery);
System.out.println("Result retreived 1");
//System.out.println('"sqlquery"');
}
catch (SQLException s)
{
System.out.println("SQL statement is not executed! "+ s);
}
}
catch (Exception e){
e.printStackTrace();
}
System.out.println("************");
//String sqlq="";
if(sqlquery.equals("1"))
{
String sqlq="select Section.Section_Name , Report.Report_Name , Report.Link, Contact.Contact_Name, Metrics.Metric_Name "
+ "FROM Section , Report , Contact,Metrics "
+ "WHERE Report.Contact_ID=Contact.Contact_ID and Report.Section_ID=Section.Section_ID "
+ "and Report.Report_ID IN (SELECT Metrics.Report_ID FROM Metrics WHERE Metrics.Metric_Name = Report.Report_ID') and Metrics.Metric_Segment = 'M' ";
System.out.println("2nd query executed too !");
try
{
Class.forName(driver);
con = DriverManager.getConnection(url, user, pass);
try
{
Statement st = con.createStatement();
System.out.println("Connection created");
ResultSet rs = st.executeQuery(sqlq);
System.out.println("Result retreived ");
while (rs.next())
{
List<String> book=new ArrayList<String>();
String Name=rs.getString("Section_Name");
String reportName=rs.getString("Report_Name");
String link=rs.getString("Link");
String contactName=rs.getString("Contact_Name");
String metricName=rs.getString("Metric_Name");
//String reportId=rs.getString("Report_ID");
/*String ind_id=rs.getString("index_name");
String ind_name=rs.getString("link_id");*/
book.add(Name);
book.add(reportName);
book.add(link);
book.add(contactName);
book.add(metricName);
//book.add(reportId);
/*book.add(ind_id);
book.add(ind_name);*/
booklist.add(book);
}
}
catch (SQLException s)
{
System.out.println("SQL statement is not executed! "+ s);
}
}
catch (Exception e) {
e.printStackTrace();
}}
System.out.println("And it came here lastly !");
request.setAttribute("booklist",booklist);
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/searchbook.jsp");
dispatcher.forward(request, response);
}
}
You're setting your variable
String sqlquery="select Index1.link_id "
+ "FROM Index1 "
+ " WHERE Index1.index_name LIKE '%"+category+"%' ";
and then comparing it to 1:
if(sqlquery.equals("1"))`
which will never be true
add a String sqlResult = null; right after your sqlquery declaration
and add a sqlResult = rs.getString(1) right after your
rs = st.executeQuery(sqlquery);
then compare with sqlResult instead of sqlQuery
I suspected that you are trying to compare "string" with "int" :
if(sqlquery.equals("1"))
So it will obviously not go inside the statement.
Instead you can try this
if(sqlquery != null)
Of course it won't. sqlquery is a string containing the SQL-code ("SELECT ...").
Your string sqlquery contains a select statement so will never be equal to "1".
You need to check the result of your query, not the query string itself.
To do that, you're going to need to define rs (and the Statement as well, I believe) before the try block (so it stays in scope after that block), then evaluate it to see if it returned the data you desired.
How you do that depends on whether that "1" is meant to represent the number of rows returned or the data itself returned (from Index1.link_id).