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.
Related
I executed the below code to create a table USER and everything looks fine since when I try to execute it again, I get the error "Table 'USER' already exists".
public static void main(String[] args) throws SQLException, ClassNotFoundException {
sqlDB mysqlConnect = new sqlDB();
Statement stmt = mysqlConnect.connect().createStatement();
String sql = "CREATE TABLE USER " +
"(id INTEGER not NULL, " +
" first VARCHAR(255), " +
" last VARCHAR(255), " +
" PRIMARY KEY ( id ))";
try {
stmt.executeUpdate(sql);
PreparedStatement statement = mysqlConnect.connect().prepareStatement(sql);
} catch (SQLException e) {
e.printStackTrace();
} finally {
mysqlConnect.disconnect();
}
}
My question is why don't I see this table in MySQL Workbench?
I checked the section 'Schemas' but there I have only 1 db 'sys' which is not the one I created.
User is a mysql system table;
You can create a new db and create the table new db.Tablename;
I am working on Java GUI application which connects to SQL database on localhost (I use XAMPP). When I change some entry, for example Age, I click on "Save changes", it is saved and changes are done in SQL database, but when I click on ">" or "<" to view next or previous person and then go back to the person, where I did changes, every entry is without changes in its initial state. But when I close the application and reopen it, all the changes which I made are done. This is part of the code where is mistake, I think. Thank you.
private void jButtonSaveChangesActionPerformed(java.awt.event.ActionEvent evt) {
try {
Statement stmt = con.createStatement();
try {
String query1 = "UPDATE list1 SET " +
"name ='" + jTextFieldName.getText() + "', " +
"surname ='" + jTextFieldSurname.getText() + "', " +
"age ='" + jTextFieldAge.getText() + "' " +
"WHERE ID = " + jLabelActualID.getText();
stmt.executeUpdate(query1);
} catch (Exception e) {
System.err.println(e);
}
} catch (Exception e) {
System.err.println(e);
}
}
Picture of application:
You are not closing, which can be done more safe and automatically with try-with-resources.
This means a commit might not have happened yet. There is an autocommit setting too.
String query1 = "UPDATE list1 SET " +
"name = ?, " +
"surname = ?, " +
"age = ? " +
"WHERE ID = ?";
try (PreparedStatement stmt = con.prepareStatement(query1)) { // Closes stmt.
stmt.setString(1, jTextFieldName.getText());
stmt.setString(2, jTextFieldSurname.getText());
stmt.setInt(3, Integer.parseInt(jTextFieldAge.getText()));
stmt.setString(4, jLabelActualID.getText());
int updateCount = stmt.executeUpdate();
} catch (SQLException | NumberFormatException e) {
System.err.println(e);
}
The same may hold (or may not hold) for the SQL connection.
Also one should use a PreparedStatement for security (SQL injection) and type safeness / escaping of backslash, quote in strings. As you see it is even more readable.
Another case is a second application accessing the database: it can use its own cache, thereby be a bit outdated.
So I am getting a database and my discord bot is connecting to the database but when I get it I am getting an error of com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'd1aa852e1a504d6cafbd55e0d2d28dea' in 'where clause'
Here is my code
int id = SQLUser.getIntFromDatabase("SELECT * FROM Players WHERE UUID = " + uuid.toString() + "", "ID");
if(id==-1) channel.sendMessage("ID is not valid please login to the WidowMC").queue();
else
{
Message messa = new MessageBuilder().append(Utils.getName(uuid) + " Skull").build();
channel.sendFile(Utils.getSkullFile(Utils.getName(uuid)), messa).queue();
channel.sendMessage("ID = " + id);
}
public static void excuteQuery(String query)
{
Connection conn = Core.getConnection();
try
{
Statement statement = conn.createStatement();
statement.executeQuery(query);
} catch (SQLException e)
{
e.printStackTrace();
}
}
You need to add quotes around the uuid to make it a literal, otherwise Mysql thinks you're referring to a column.
Also be very careful, your code is vulnerable to SQL injection, use the Prepared Stamements correctly could help you removing the vulnerability.
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");
I am using hadoop-1.0.4 and hive-0.10.0 in redhat5. Service start successfully. I am able to create, drop, select table easily but I don't know how to insert data.
For example I have two text box and on button click I want to store data in table (userInfo). I have no clue how to store textbox vaue in userInfo(id,password).
private static String driverName = "org.apache.hadoop.hive.jdbc.HiveDriver";
try {
Class.forName(driverName);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(1);
}
Connection con = DriverManager.getConnection("jdbc:hive://localhost:10000/enggheads","", "");
Statement stmt = con.createStatement();
String tableName = "testHiveDriverTable";
stmt.executeQuery("drop table " + tableName);
ResultSet res = stmt.executeQuery("create table " + tableName + " (key int, value string)");
// show tables
String sql = "show tables '" + tableName + "'";
System.out.println("Running: " + sql);
res = stmt.executeQuery(sql);
if (res.next()) {
System.out.println(res.getString(1));
}
It's Java, but I don't know how to insert two field value because Hive insertion is different than MySQL or other database syntax.
Create a dummy table in hive like below
create table dummy(dummy string) location '/path';
Above path will have a file which contains data X
Now run insert query from jdbc driver like below.
insert into table tblname select forntendvalue1,frontendvalue2 from dual;