I am working on a school project where I must interact with an access database. I'm attempting to
SELECT Max(GameID) AS MaxID
FROM Games
However, This query when ran through the Eclipse application I built only returns in the console
SQL Exception: UCAExc:::4.0.3 Column not found: GameID
SQL State: S1000
Vendor Error: -421
I have checked the access database and the column DEFINITELY EXISTS. I ran the query in the access database and it worked in there as well. I'm not sure what I'm missing or if this is possible. How can i grab the highest value of gameID's?
here is the connection to the database
ResultSet rs = null; //will hold record that get returned
Statement stmt = null; //will hold the SQL statement we want to run
try
{
//2. Establish the connection
Connection conn = DriverManager.getConnection("jdbc:ucanaccess://C:/Users/Public/ZaccaroBlottoDB.accdb");
//3. Create the statement
stmt = conn.createStatement();
String theQuery = "SELECT Max("
+ "GameID)"
+ " As MaxID"
+ " FROM Games"
+ " WHERE (1=1)";
//4. Execute the statement
rs = stmt.executeQuery(theQuery);
//5. Process the results
while (rs.next())
{
int gameID = rs.getInt("GameID"); //note the type and the field name from the DB
System.out.println(gameID);
//addGameIDFTF.setText(Integer.toString(gameID +1));
}//while
//6. Close the Connection
rs.close();
conn.close();
}
catch (SQLException ex)
{
System.out.println("SQL Exception: " + ex.getMessage());
System.out.println("SQL State: " + ex.getSQLState());
System.out.println("Vendor Error: " + ex.getErrorCode());
ex.printStackTrace();
} //catch
I think the issue is the value that you are retrieving. As you have mentioned the alias name to be MaxID you should get MaxID from result_set instead of GameID
Hence, It should be
int gameID = rs.getInt("MaxID");
instead of
int gameID = rs.getInt("GameID");
Related
I created a class (ValidarStatusOsPage) in java that makes a connection to the DB and returns to a test class (ValidateStatusOsTest) the result of the query and prints to the screen.
When I run the test class, the Eclipse console displays the message:
ORA-00923: FROM keyword not found where expecte
I have reviewed the code several times but I can not verify where the error is.
Below is the Java class for connecting to the DB and the test class.
public class ValidarStatusOsTest {
static String query;
#Test
public void validarOs() {
ValidarStatusOsPage os = new ValidarStatusOsPage();
query = os.returnDb("179195454");
}}
public class ValidarStatusOsPage {
String resultado;
public String returnDb(String NuOs) {
// Connection URL Syntax: "jdbc:mysql://ipaddress:portnumber/db_name"
String dbUrl = "jdbc:oracle:thin:#10.5.12.116:1521:desenv01";
// Database Username
String username = "bkofficeadm";
// Database Password
String password = "bkofficeadmdesenv01";
// Query to Execute
String query = "SELECT NU_OS, CD_ESTRATEGIA, CD_STATUS, NU_MATR, DT_ABERTURA" +
"FROM tb_bkoffice_os"+
"WHERE NU_OS ="+ NuOs +"";
try {
// Load mysql jdbc driver
Class.forName("oracle.jdbc.driver.OracleDriver");
// Create Connection to DB
Connection con = DriverManager.getConnection(dbUrl, username, password);
// Create Statement Object
Statement stmt = con.createStatement();
// Execute the SQL Query. Store results in ResultSet
ResultSet rs = stmt.executeQuery(query);
// While Loop to iterate through all data and print results
while (rs.next()) {
String NU_OS = rs.getString(1);
String CD_ESTRATEGIA = rs.getString(2);
String CD_STATUS = rs.getString(3);
String NU_MATR = rs.getString(4);
String DT_ABERTURA = rs.getString(5);
resultado = NU_OS + " " + CD_ESTRATEGIA + " " + CD_STATUS + " " + NU_MATR + " " + DT_ABERTURA + "\n";
System.out.println(NU_OS + " - " + CD_ESTRATEGIA + " - " + CD_STATUS + " - " + NU_MATR + " - "+ DT_ABERTURA);
}
// closing DB Connection
con.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return resultado;
}}
3 points are there in your query:
SELECT NU_OS, CD_ESTRATEGIA, CD_STATUS, NU_MATR, DT_ABERTURA" +
"FROM tb_bkoffice_os"+
"WHERE NU_OS ="+ NuOs +""
space before FROM missed first part of query is: SELECT NU_OS, CD_ESTRATEGIA, CD_STATUS, NU_MATR, DT_ABERTURAFROM
space missed before WHERE: SELECT NU_OS, CD_ESTRATEGIA, CD_STATUS, NU_MATR, DT_ABERTURAFROM tb_bkoffice_osWHERE NU_OS =
concatenate parameter into SQL string is exact hack point for SQL Injection attack. Never do it in real program even if it is pure standalone. Always use parameters for queries.
and a little last one: + NuOs +"" - last "" has no sense at all...
good luck.
UPD: #YCF_L absolutely right use Prepared statement.
you need to do this:
in Sql String: WHERE NU_OS = ?
in code:
PreparedStatement stmt = con.prepareStatement(query);
stmt.setString(1, NuOs);
//also works: stmt.setObject(1,NuOs);
things to remember with JDBC:
all parameters in SQL are just ? marks
parameter indexes start with 1 (not 0)
and in order they appear in SQL from strat to end
(e.g. Select * FROM tbl WHERE col1=? and col2=?
has parameter 1 for col1 and parameter 2 for col2
PS. your initial SQL has one more error but I'm not going to tell you what is it :-) use parameter and all be fine.
This is driving me mad because I cannot make any sense of it. I am executing the following code:
nameString = jcbClientList.getItemAt(jcbClientList.getSelectedIndex());
System.out.println(" Name String = " + nameString );
sql = "SELECT * FROM clients WHERE Name = \'" + nameString + "\'";
System.out.println(sql);
try {
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
while( rs.next()) {
clientID = rs.getInt(1);
}
}
catch(SQLException se) {
msg = "Problem getting client ID from DB \n" + se.getLocalizedMessage();
System.out.println(msg);
JOptionPane.showMessageDialog(null, msg);
}
The SQL string be built is correct. I have checked this by taking the System.out.println(sql) output of the string and pasting it into other code and it work perfectly. However, in this context I am getting an exception:
Invalid cursor state - no current row.
Even if I change the sql to be 'SELECT * FROM clients' which should return 20 rows and does elsewhere in the application, it still gives the same error. The database being addressed is an embedded Derby DB.
I seem to recall having run into specific JDBC drivers that did not properly implement the part that says " A ResultSet cursor is initially positioned before the first row ". I got around it by first doing a first() (or beforeFirst()) call and only then start invoking next().
I'm learning how to implement a database into a music player application, and decided to use the embedded H2 database for my implementation.
public class H2EmbeddedDB {
public H2EmbeddedDB() {
try {
Class.forName("org.h2.Driver");
Connection conn = DriverManager.getConnection("jdbc:h2:~/data/musicAppDB", "sa", "");
Statement st = conn.createStatement();
/*
String createTableSQL = "CREATE TABLE PLAYLISTS " +
"(playlistID INTEGER not NULL, " +
" playlistName VARCHAR(255), " +
" musicToContinuePath VARCHAR(255), " +
" durationToContinue INTEGER)";
st.execute(createTableSQL);
*/
String sql = "INSERT INTO PLAYLISTS " + "VALUES (123456789, 'Zara', 'C:\\Music', 18)";
st.executeUpdate(sql);
ResultSet rs;
rs = st.executeQuery("select * from playlists");
while (rs.next()) {
System.out.println(rs.getString("playlistName"));
}
conn.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Just a simple test class, I commented out the create table after the table is created. Everything works fine, the application prints out 'Zara' like it should, but I cannot find the table in the Intellij Database Tool.
[How I'm importing the database]
https://i.gyazo.com/e2c1360729d53f837ffe3195290db7fa.png
[Not showing anything in the DB]
https://gyazo.com/4ddc9cea065bd928471aff0805130f73
I know where it is storing the database, it's in my user folder/data, and I've tried putting the absolute path to it when connecting with intellij client. The connection test succeeds as well.
I am trying to connect to sql server 2005 from my Java application using
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionurl = "jdbc:sqlserver://servername\\SQLEXPRESS;" + "database=master";
Connection con = DriverManager.getConnection(connectionurl);
System.out.println("Connected to SQL Server");
String sql = "select * from employee";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
System.out.println(rs.getString(1) + " " + rs.getString(2));
}
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
On executing it, I do not get any output / error at the console. What am I missing?
Maybe there is no records in the table employee.
Or it throws an Exception whose e.getMessage() returns ""(I don't think so,but to avoid it,You can use e.printStackTrace() instead).
actually,the correct answer is...
when you insert the record in sql prompt we have to commit that record by command commit;
sql>commit;
even thought when you insert the record after that you can check by command select *from table;
record is inserted successfully...record is there
but in command prompt when we executing java program records are not displaying....
so commit the record when u inserted..
thankyou
I m new to mysql and m trying to select N rows from a mysql table in eclipse. Now, i want to select N rows of same value from the database. I am using the following code
User user= null;
ArrayList<User> searchedUsers = new ArrayList<User>();
PreparedStatement stmt = null;
ResultSet rs = null;
try {
String authenticationSql;
authenticationSql = "SELECT * FROM users WHERE " + searchIn + " = ?";
log.info(authenticationSql);
stmt = (PreparedStatement) dbConn.prepareStatement(authenticationSql);
stmt.setString(1, searchFor);
rs = stmt.executeQuery();
while (rs.next()) {
user = new User(rs.getString("username"),
rs.getInt("user_type"), OnlineStatus.ONLINE);
searchedUsers.add(user);
}
rs.close();
stmt.close();
} catch (SQLException ex) {
log.error("SQLException: " + ex.getMessage());
log.error("SQLState: " + ex.getSQLState());
log.error("VendorError: " + ex.getErrorCode());
}
The problem is this code only returns me the first value of the search and not the rest of the values are selected from the database. Can please some one point out what i m doing wrong here. Any help will be appreciated. Thanks.
You cannot use count(*) in statement like this.
It should give you some error like Mixing of GROUP columns (MIN(),MAX(),COUNT(),...) with no GROUP columns is illegal if there is no GROUP BY clause
I think it's the COUNT(*) from your SELECT that is grouping your results. Try without it