I am trying to create a query for past orders from a oracle database and i want to search by Company name.
I am not sure where to start with accessing the database
Here is the basic command line prompt i created but i not sure
import java.util.Scanner;
public class PastOrders {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
system.out.prinln("Welcome to Company XYZ Order Query");
system.out.println();
Sting companyName;
System.out.print("Enter Company Name to pull up previous orders: ";
}
}
First of all, you need to download and the Java Data Base Connector (JDBC) for you Database. For oracle you can find it here: http://www.oracle.com/technetwork/apps-tech/jdbc-112010-090769.html
Then you have to set up a connection, write and execute a query, like this (http://docs.oracle.com/javase/tutorial/jdbc/overview/index.html):
import java.sql.*;
public class UpdateCar {
public static void UpdateCarNum(int carNo, int empNo)
throws SQLException {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DriverManager.getConnection(
"jdbc:default:connection");
pstmt = con.prepareStatement(
"UPDATE EMPLOYEES " +
"SET CAR_NUMBER = ? " +
"WHERE EMPLOYEE_NUMBER = ?");
pstmt.setInt(1, carNo);
pstmt.setInt(2, empNo);
pstmt.executeUpdate();
}
finally {
if (pstmt != null) pstmt.close();
}
}
}
The only thing you have to change in this sample code is the PreparedStatement(psmt - query) and the Connection(con).
Related
I am connecting my Java Program to a database stored in the program folder, and I am having users answer quiz questions and I want the results to be stored in the database. The Update statement is not working, and I don't know if it's a problem with the actual statement or the database connection.
I've tried creating a new database with the same tables and reconnecting to that database, but nothing seems to be working.
//database connection class
public class databaseConnection {
public static Connection dbConnector() {
try {
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager
.getConnection("jdbc:sqlite:D:\\Users\\mariammahmoud\\eclipse-workspace\\ia_2019_final\\testjava.db");
return conn;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
return null;
}
}
}
public class student {
public static final String DB_NAME = "testjava.db";
public static final String TABLE_STUDENTS = "students";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_GRADE = "grade";
public static final String COLUMN_RESULTS = "results";
public static final String COLUMN_EVENTS = "events";
public static final String COLUMN_USERNAME = "username";
public void main() {
try {
String user_name = login_student.sendQuiz();
Connection conn = databaseConnection.dbConnector();
ArrayList<String> results = new ArrayList<String>(15);
instructions();
questions(results);
results.trimToSize();
System.out.println("Here are the events that you should consider competing in:");
System.out.println(results);
String separator = ",";
int total = results.size() * separator.length();
for (String finalResults : results) {
total += finalResults.length();
}
StringBuilder sb = new StringBuilder(total);
for (String finalResults : results) {
sb.append(separator).append(finalResults);
}
String resultsDatabase = sb.substring(separator.length());
String sql = "UPDATE students SET events = ? WHERE username = " +user_name;
PreparedStatement myStmt = conn.prepareStatement(sql);
myStmt.setString(1, resultsDatabase);
myStmt.executeUpdate();
} catch (SQLException e) {
System.out.println("Something went wrong:" + e.getMessage());
e.printStackTrace();
}
}
I expected the update statement to update the testjava.db database, but everything is staying the same. What should I do? Thank you in advance!
Your problem is that while you wisely used a prepared statement in your code for the update, you never actually used it for the username column in the WHERE clause. Hence, the query you are executing currently won't be interpreted as comparing some input against username. Rather, the username value will be interpreted as a column. Try this version:
String resultsDatabase = sb.substring(separator.length());
String sql = "UPDATE students SET events = ? WHERE username = ?";
PreparedStatement myStmt = conn.prepareStatement(sql);
myStmt.setString(1, resultsDatabase);
myStmt.setString(2, user_name);
myStmt.executeUpdate();
Note that you could have just tried the following:
String sql = "UPDATE students SET events = ? WHERE username = '" + user_name + "'";
But, please bind a value to a ? placeholder instead, as I have suggested above. One benefit of using statements is that it frees you from having to worry about how to escape your data in the query.
I'm having a problem with my derby engine.
When I make a new database , create new tables and insert or display rows , everything works fine. And when I try to use the database in my practice example , the database works fine and I'm able to insert and select data from the table.
Code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSetMetaData;
public class Restaurants
{
private static String dbURL = "jdbc:derby:c:\\Apache\\db-derby-10.14.2.0-bin\\bin\\myDBExample;create=true";
private static String tableName = "restaurants";
// jdbc Connection
private static Connection conn = null;
private static Statement stmt = null;
public static void main(String[] args)
{
createConnection();
//insertRestaurants(5, "LaVals Leb", "Berkeley");
//insertRestaurants(6, "House Leb", "New York");
selectRestaurants();
shutdown();
}
private static void createConnection()
{
try
{
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
//Get a connection
conn = DriverManager.getConnection(dbURL);
}
catch (Exception except)
{
except.printStackTrace();
}
}
private static void insertRestaurants(int id, String restName, String cityName)
{
try
{
stmt = conn.createStatement();
stmt.execute("insert into " + tableName + " values (" +
id + ",'" + restName + "','" + cityName +"')");
stmt.close();
}
catch (SQLException sqlExcept)
{
sqlExcept.printStackTrace();
}
}
private static void selectRestaurants()
{
try
{
stmt = conn.createStatement();
ResultSet results = stmt.executeQuery("select * from " + tableName);
ResultSetMetaData rsmd = results.getMetaData();
int numberCols = rsmd.getColumnCount();
for (int i=1; i<=numberCols; i++)
{
//print Column Names
System.out.print(rsmd.getColumnLabel(i)+"\t\t");
}
System.out.println("\n-------------------------------------------------");
while(results.next())
{
int id = results.getInt(1);
String restName = results.getString(2);
String cityName = results.getString(3);
System.out.println(id + "\t\t" + restName + "\t\t" + cityName);
}
results.close();
stmt.close();
}
catch (SQLException sqlExcept)
{
sqlExcept.printStackTrace();
}
}
private static void shutdown()
{
try
{
if (stmt != null)
{
stmt.close();
}
if (conn != null)
{
DriverManager.getConnection(dbURL + ";shutdown=true");
conn.close();
}
}
catch (SQLException sqlExcept)
{
}
}
}
This code works fine but when I try to create a connection to the same database again with ij , I get an error in my command prompt like this:
In the image, the upper part is when I first make my database but after that when I use it in eclipse, it gives me this error. Even using a db in eclipse once will result in this error.
What is the issue? Why is derby engine not getting the access granted to it?
Any help is appreciated.
I suspect that you confused the database modes here. In your question's title you mention "embedded Derby", but you're code is using the ClientDriver and the create=true attribute, which does create the DB if it doesn't exist, but it doesn't start the server.
If you don't want to start the server, you can just use the EmbeddedDriver.
Another point where you might run into problems is with the shutdown=true attribute. You're using the entire DB URL (dbURL) including the filename, but if you want to shut down the server from your code, you should omit the filename, like this : jdbc:derby:;shutdown=true.
You can check out the Derby developer docs for information on using these attributes, and the Embedded Derby tutorial for using Derby in embedded mode, sou you won't have to worry about starting the server.
Found out the issue. I had to start the derby as a network server on the port by using the following command:
startNetworkServer.bat
I'm learning MySQL and I get this problem:
No suitable driver found for jdbc:mysql//localhost:3306/demo?useSSL=false
I have read other solutions but it's not working.
This is my code:
package jdbc.test;
import java.sql.*;
public class JdbcInsertDemo {
public static void main(String[] args) throws SQLException {
Connection myConn = null;
Statement myStmt = null;
ResultSet myRs = null;
String dbUrl = "jdbc:mysql//localhost:3306/demo?useSSL=false";
// jdbc:mysql//localhost:3306/demo?useSSL=false
String user = "student";
String pass = "student";
try {
myConn = DriverManager.getConnection("jdbc:mysql//localhost:3306/demo?useSSL=false", user, pass);
myStmt = myConn.createStatement();
System.out.println("Inserting a new employee to database\n");
int rowsAffected = myStmt.executeUpdate("Insert into employees" + "(last_name, first_name, email, department, salary)" + "values" + "('Wright' , 'Eric', 'eric.wright#foo.com', 'HR', 33000.00)");
myRs = myStmt.executeQuery("slect * from employees order by last_name");
while(myRs.next()) {
System.out.println(myRs.getString("last_name") + ", " + myRs.getString("first_name"));
}
}
catch(Exception exc) {
exc.printStackTrace();
}
finally {
if (myRs != null) {
myRs.close();
}
}
}
}
I think you forgot to include jar file in lib folder. Put the drive jar file in that folder and try again.
Theres a few things that could be wrong.
1 : Do you have the JDBC Jar included in the project references?
myConn = DriverManager.getConnection("jdbc:mysql//localhost:3306/demo?useSSL=false", user, pass);
Also, for shorthand, since you have 'DbUrl' - MyConn can be simplified.
String dbUrl = "jdbc:mysql//localhost:3306/demo?useSSL=false";
myConn = DriverManager.getConnection(dbUrl, user, pass);
You have missed the
Class.forName("com.mysql.jdbc.Driver");
This line needs to be added before you get the connection object.
Can someone please tell me what is wrong to my query.
I have textbox to update the occupantname but it doesn't work, Only Status works.
String gOccupied = "Occupied" ;
String query = "UPDATE `rooms` SET `occupantname` = '"+txtFirstNames.getText()+"' , `status`='"+gOccupied+"' WHERE roomnumber = " +CBRoomNumber.getSelectedItem();
executeSQlquery(query,""+" Updated");
Can someone please tell me what is wrong to my query. i have textbox
to update the occupantname but it doesn't work, Only Status works.
Don't use direct MySql SQL with these special characters `
String query = "UPDATE rooms SET occupantname =
'"+txtFirstNames.getText()+"' , status='"+gOccupied+"' WHERE
roomnumber = " +CBRoomNumber.getSelectedItem();
Blockquote
Instated Use below SQL
String query = "UPDATE rooms SET occupantname = ? , status= ? WHERE roomnumber = ?";
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Main {
private static PreparedStatement preparedStmt = null;
private static Connection connection = null;
public static void main(String[] args) {
String gOccupied = "Occupied";
String occupantname = txtFirstNames.getText();
String query = "UPDATE rooms SET occupantname = ? , status= ? WHERE roomnumber = ?";
try {
executeSQlquery(query, occupantname, gOccupied, "Updated");
} catch (Exception e) {
e.printStackTrace();
}
}
private static void executeSQlquery(String query, String occupantname, String gOccupied, String status) throws SQLException {
try {
// create a java mysql database connection
String myDriver = "org.mysql.Driver";
String myUrl = "jdbc:mysql://localhost/test";
Class.forName(myDriver);
connection = DriverManager.getConnection(myUrl, "username", "password");
preparedStmt = connection.prepareStatement(query);
preparedStmt.setString(1, occupantname);
preparedStmt.setString(2, gOccupied);
preparedStmt.setInt(3, 101);
// execute the java preparedstatement
preparedStmt.executeUpdate();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
//finally block used to close resources
if (preparedStmt != null) {
connection.close();
}
if (connection != null) {
connection.close();
}
}
}
}
It is generally a terrible idea to construct SQL queries the way you currently do, as it opens the door to all sorts of SQL injection attacks. To do this properly, you'll have to use Prepared Statements instead. This will also resolve all sorts of escaping issues that you're evidently having at the moment.
SQL select statement with where clause
Well, I'm trying to use SQLite in my Libgdx game, but don't know how.
public class Main {
public static void main(String[] args){
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
config.title = Game.TITLE;
config.width = Game.V_WIDTH * Game.SCALE;
config.height = Game.V_HEIGHT * Game.SCALE;
new LwjglApplication(new Game(), config);
}}
What I need to do in my main? lol
I've been looking for this but, all I can find is related to Android application.
I already have the driver in my ref libraries, and connection class..
What I usually do when using a database with an application, is make a ConnectionFactory, that returns a new connection to the database.
public class ConnectionFactory {
public static Connection getConnection() {
Connection con = null;
Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("jdbc:sqlite:test.db"); //change to whatever db you want
return con;
}
}
now we have a ConnectionFactory that can pump out connections to our database. Now when we want to interact with the database, you can get the connection appropriately. inside your main, it might look something like this:
public static void main(String[] args) {
Connection con = null;
String firstName = null, lastName = null;
try {
con = ConnectionFactory.getConnection();
PreparedStatement pstmt = con.prepareStatement("SELECT * FROM myTable where myId = ?");
pstmt.setInt(1, /*some id here, ill put this as example:*/ 1234567);
//execute the query and put into result set so we can get the values.
ResultSet rs = pstmt.executeQuery();
//the resultset iterates through rows, by calling next
if( rs.next() ) //could be while(rs.next()) if expecting multiple rows
{
firstName = rs.getString("firstName"); //column name you want to grab here
lastName = rs.getString("lastName");
}
} catch(SQLException sqle) {
sqle.printStackTrace();
}
finally {
try {
con.close(); //dont forget to close your connection to database!
} catch(SQLException sqle) {
sqle.printStackTrace();
}
}
}
You will need to create tables within the SQLite database and insert records before you can do any interactions though, so keep that in mind.