I have a postgres database and a table named "state_master". I'm simply fetching the data from this table by the following code.
import java.sql.*;
public class Test1
{
public static void main(String... s1)
{
try{
Class.forName("org.postgresql.Driver");
Connection con = DriverManager.getConnection("jdbc:postgresql://localhost:5432:secc_db","postgres", password");
Statement s = con.createStatement();
ResultSet rs = s.executeQuery("Select * from state_master");
}catch(SQLException e){ System.out.println(e);}
catch(Exception i){System.out.println(i);}
}
}
All I get is an error: relation state_master does not exist. Please help me to sort out this problem.
The erroe means the table state_master is not exist in the user(Database) postgres. Check whether you have created the table state_master in your database or not. If not first create the table then try to execute the program.
Your connect url is not correct. you are using colon(:) for specifying the database.
It should be a slash(/) like : "jdbc:postgresql://localhost:5432/secc_db"
Related
I'm not sure why my program isn't creating the table but I also need some ideas on how to fill the table with code like this once it's created? I need to add two more tables to this database too.
This is the error I'm getting :
java.sql.SQLSyntaxErrorException: Table/View 'PIZZASIZE' does not exist.
Caused by: ERROR 42X05: Table/View 'PIZZASIZE' does not exist.
Caused by: java.lang.RuntimeException: Exception in Application start method
Caused by: javafx.fxml.LoadException: file:/C:/Users/Allie/Documents/NetBeansProjects/Pizzeria_AllieBeckman/dist/run1674141987/Pizzeria_AllieBeckman.jar!/pizzeria_alliebeckman/FXMLDocument.fxml
This is the code that's supposed to create the table:
// connect to the derby URL using the given username and password
connect = DriverManager.getConnection("jdbc:derby://localhost:1527/pizzeria;create=true", connectProps);
// current url for pre created database "jdbc:derby://localhost:1527/pizza"
// if connection is successful print that it succeeded.
System.out.println("database created");
stmt = connect.createStatement();
String sqlCreate = "CREATE TABLE PIZZASIZE "
+ "(id int NOT NULL, "
+ "size char(20) NOT NULL, "
+ "PRIMARY KEY (id))";
stmt.execute(sqlCreate);
Depending on the IDE you are using you could manually create the table in a console without going through the trouble of writing it in code. Here are some examples of how you could get the information from the tables.
Connection conn = CreatingDerbyDJB.dbConnection();
try{
String query = "INSERT INTO Items (Name,Color,ItemName,SchoolName, Description) VALUES(?,?,?,?, ?)";
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.execute();
conn.close();
}catch(Exception e)
{
e.printStackTrace();
} }
Here is what the Connection class should look like:
package main;
import java.sql.Connection;
import java.sql.DriverManager;
import javax.swing.JOptionPane;
public class CreatingDerbyDJB
{
public static final String DRIVER = "org.apache.derby.jdbc.EmbeddedDriver";
public static final String JDBC_URL = "jdbc:derby:LostAndFoundDB";
public static Connection dbConnection()
{
try
{
Class.forName(DRIVER).newInstance();
Connection c = DriverManager.getConnection(JDBC_URL);
return c;
}catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
return null;
}
}
}
Approve this answer if this helped you, I'd be happy to explain things if it does not make sense. :)
I am following a tutorial on connecting my SQLite database to a Java application.
When I run the program I get the following error in the console of NetBeans:
run:
Error connecting to the databasejava.sql.SQLException: No suitable
driver found for jdbc:C:\Users\lawman\Documents\Java Working
Directory\LoginSql\src\project123.sqlite
BUILD SUCCESSFUL (total time: 0 seconds)
Here is my directory:
I have code to connect to the database in class tobecalledbymain.
I have main in mainclass which creates an instance of tobecalledbymain.
In my library file, I have sqlite-jdbcs.jar imported.
Here is the code for tobecalledinmain:
import java.sql.*;
public class tobecalledinmain {
public tobecalledinmain(){
Connection con = null;
Statement st=null;
ResultSet rs=null;
try
{
Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("jdbc:C:\\Users\\lawman\\Documents\\"
+ "Java Working Directory\\LoginSql\\"
+ "src\\project123.sqlite");
st=con.createStatement();
//select all records from the table employee
//table has three firlds: employeeid,name and surname
rs=st.executeQuery("SELECT * FROM Employee;");
while (rs.next())
{
int id = rs.getInt("Employeeid");
String name = rs.getString("Name");
System.out.println("id = " + id);
System.out.println("name= " + name);
System.out.println();
}
rs.close();
st.close();
con.close();
}catch(Exception e)
{
System.out.println("Error connecting to the database" + e);
}
}
}
Here is the mainclass code:
public class mainClass {
public static void main(String[] args){
new tobecalledinmain();
}
}
;;
I am not sure why we need to semi-colons!
Anyway, when the tutorial concludes he gets a result from the console. I get the said error message.
What are the drivers in the error message referring to and how do I get them?
Your jdbc connection string does not specify sqlite. Try this, and use forward slashes.
Connection con = DriverManager.getConnection("jdbc:sqlite:C:/PATH/TO/database.db");
This was the WRONG answer, pls disregard.
You need to add the .jar for the SQLite database driver to your classpath when you run your code. See https://bitbucket.org/xerial/sqlite-jdbc
You can see how to do that in Netbeans here: How to add a JAR in NetBeans
I have created a simple database application with Java and MySQL. I would like for the use to specify what they want to call the database and then have it created. I get an SQL syntax error when I run the following code:
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
try{
Class.forName("com.mysql.jdbc.Driver");
connect.con = DriverManager.getConnection("jdbc:mysql://localhost/?user=root&password=pass");
connect.st = connect.con.createStatement();
String dbName = jTextField19.getText().trim();
System.out.println(dbName);
String sql = "CREATE DATABASE'"+dbName+"'";
int rs = connect.st.executeUpdate(sql);
System.out.println("Database Created");
}catch(Exception e){
}
}
What am I doing wrong? An explanation is much appreciated.
"CREATE DATABASE'"+dbName+"'";
should be (note the additional space):
"CREATE DATABASE "+dbName;
I have a following cassandra table "users" defined in keyspace "chemdb"
CREATE TABLE users (
userid text PRIMARY KEY,
passwd text,
fname text,
lname text,
creationdate timestamp,
isactive text
);
I created a java class JDBConnec.java to connect jsp with cassandra using jdbc:
package dbclasses;
import java.sql.*;
import java.lang.*;
import java.io.*;
public class JDBConnec {
public Statement stmt=null;
public ResultSet rs=null;
public Connection con=null;
public PreparedStatement pstmt = null;
public JDBConnec()
{
try
{
Class.forName("org.apache.cassandra.cql.jdbc.CassandraDriver");
con = DriverManager.getConnection("jdbc:cassandra://127.0.0.1:9160/chemdb","okkkkk","12345");
}
catch(Exception ex)
{
System.out.println(ex.getMessage());
}
}
}
The above class is succesfully compiling.
However in my jsp file, when I use the following code to select record from database by using Preparedstatements, I get the below mentioned error:
JDBConnec db = new JDBConnec();
String query = "select * from users where userid=?";
db.pstmt = db.con.prepareStatement(query);
db.pstmt.setString(1, "henry");
db.rs = db.pstmt.executeQuery();
It gives following error
InvalidRequestException(why:Undefined name userid in where clause ('userid EQ ?'))
Does cassandra jdbc driver support preparedstatments in jsp? Any thoughts on why this error is occuring. Thanks in advance.
Cassandra version: 2.0.8
Java: 7
Apache tomcat: latest downloaded yesterday
I was able to figure out problem. I just changed the query from
String query = "select * from users where userid=?";
to
String query = "select userid, passwd from chemdb.users where userid=?";
and it worked fine.
Thanks!
So I am trying to connect to my database and display an item from the table.
The error I am getting is: SQL Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Access denied for user 'Bob'#'%' to database 'TEST'
Is this connecting properly, and if so is the error that the credentials are wrong? And if they are wrong how is it connecting? Thank you
try
{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://THISISTHEHOSTNAME";
String username = "Bob";
String password = "password";
Connection connection = DriverManager.getConnection(url, username, password);
Statement stmt = null;
ResultSet rs = null;
//SQL query command
String SQL = "SELECT * FROM TEST";
stmt = connection.createStatement();
rs = stmt.executeQuery(SQL);
while (rs.next())
{
System.out.println(rs.getString("ProductName") + " : " + rs.getString("UnitPrice"));
}
}
catch (SQLException e)
{
System.out.println("SQL Exception: "+ e.toString());
}
catch (ClassNotFoundException cE)
{
System.out.println("Class Not Found Exception: "+ cE.toString());
}
You need to grant the proper privileges to the user that is connecting to the mysql db.
The message you are getting is informing you that while your user was able to connect to the database server, it was not allowed to access the database TEST.
Running the following command in the mysql console would grant such access:
GRANT ALL ON TEST.* TO 'BOB'#'%'
This is extremely permissive and you should keep in mind that db users should have the minimal amount of privileges possible and be restricted to the smallest range of hosts.
I used ShowIP Firefox add on and used the IP instead and didn't get any errors but I'm wondering if should return access granted and I'm unable to find an answer at the moment.
Here's a few things to do:
Check to see if your username and password are correct.
Did you add the username to the correct database? (This needs to be done in CPanel SQL)
Did you allow your database to get connection access from your IP address? (This also needs to be done in CPanel SQL)
create a new user in mysql check all global privileges > go to service in netbeans > database > mysql server at localhost > right click connect and fill username password
this work for me
Please try the code below:
import java.sql.*;
public class InsertPrepared {
public static void main(String[] args)
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306//test","sanjib","");
PreparedStatement stmt=con.prepareStatement("insert into employee values(???)");
stmt.setInt(1,101);
stmt.setString(2,"Sampa");
int i=stmt.executeUpdate();
System.out.println(i+"Records is inserted");
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}