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
Related
I'm trying to run a statement on the java main file and I'm able to connect to the data base, but not run the sql statement
my code is:
try {
System.out.println("Connecting to the database...");
conn=DriverManager.getConnection(DB_URL,USER,PASS);
System.out.println("Connected to database successfully");
System.out.println("Inserting");
stmt=conn.createStatement();
String sql="USE TheEmployeeDatabase" +
"SELECT * FROM EmployeeTable";
stmt.executeUpdate(sql);
System.out.println("worked");
} catch (SQLException e) {
e.printStackTrace();
}
and getting the error
You have an error in your SQL syntax
As long as the schema name TheEmployeeDatabase1 is part of your DB_URL, you don't need to have the USE TheEmployeeDatabase statement.
You statement should just be:
SELECT * FROM EmployeeTable
String sql="USE TheEmployeeDatabase " <--- you need whitespace here or you will have TheEmployeeDatabaseSELECT concatenated
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");
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().
In my Struts2 Java web application users are allowed to query the database. As an example, the user needs to get the employee details whose first name is equal to 'Charles'. Then s/he can select the report columns and criteria (firstname='Charles').
Once the user gives above inputs it need to save the relevant SQL query into the database.
e.g. SQL -> SELECT * FROM employee WHERE firstname='Charles'
Here is what I am trying in my action class.
try {
connection = DriverManager.getConnection(
SelectAction.getDatabase(), SelectAction.getUser(),
SelectAction.getPassword());
if (connection != null) {
System.out.println("Database connection established!");
stmt = connection.createStatement();
String sql = "INSERT INTO reports (report_id, sql) values ('" + reportId + "', '" + sqlQ + "');";
System.out.println("sql--->" + sql);
// Executing query
stmt.executeQuery(sql);
return SUCCESS;
} else {
System.out.println("----Failed to make connection!");
return ERROR;
}
} catch (SQLException e) {
System.out.println("Connection Failed!!");
e.printStackTrace();
return SUCCESS;
}
This is my insert query.
INSERT INTO reports (report_id, sql) values ('mynewreport', 'SELECT * FROM employee WHERE firstname='Charles'');
I am getting following error in my console.
ERROR: syntax error at or near "Charles"
I think here I am using a String so that the problem is with quotes('). I am using postgreSQL as database.
Any suggestions to solve this issue ?
Never use string concatenation of user supplied values to build a SQL statement.
Never use string concatenation of any non-integer values to build a SQL statement.
You will leave yourself open to SQL Injection attacks and/or SQL statement errors.
Hackers will love you for allowing them to steal all your data, and the nefarious ones will corrupt or delete all your data, while laughing maniacally at you on their way to the bank.
Use PreparedStatement and parameter markers.
String sql = "INSERT INTO reports (report_id, sql) values (?, ?)";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, reportId);
stmt.setString(2, sqlQ);
stmt.executeUpdate();
}
I am trying to insert an email ID to a table in my SQLite3 Database. In my case it successfully creates the table but gives an error while inserting a record in it - "near "#gmail": syntax error". How can i resolve this ? Here is the code -
public void insertData(String emailId, double gtse, long receivedDate) throws ClassNotFoundException, SQLException{
Class.forName("org.sqlite.JDBC");
Connection connection = null;
try
{
// create a database connection
connection = DriverManager.getConnection("jdbc:sqlite:testdb.sqlite");
Statement statement = connection.createStatement();
statement.setQueryTimeout(30); // set timeout to 30 sec.
ResultSet result = statement.executeQuery("SELECT name FROM sqlite_master WHERE type='table' AND name='T1'");
if(!result.next()){
statement.executeUpdate("create table T1 (email TEXT, gtse REAL, receiveddate DATE)");
statement.executeUpdate("insert into T1 values(" + emailId + ", "+ gtse +", "+ receivedDate +")");
}
else{
}
}
catch(SQLException e)
{
// if the error message is "out of memory",
// it probably means no database file is found
System.err.println(e.getMessage());
}
finally
{
try
{
if(connection != null)
connection.close();
}
catch(SQLException e)
{
// connection close failed.
System.err.println(e);
}
}
}
Your core error is that for the insert query you are not enclosing the values to be inserted, in quotes. Your query, after construction, looks something like this:
insert into T1 values(whatever#gmail.com, emailtexthere, 04-07-2013)
When it should be something like this:
insert into T1 values('whatever#gmail.com', 'emailtexthere', '04-07-2013')
The SQL parser chokes while trying to parse your current query, because the syntax is incorrect. The solution to this problem is not simply to enclose the values in quotes though, but rather to use prepared statements. This is because the way you are constructing your query right now is vulnerable to SQL injection attacks. Here is an example of using a prepared statement:
PreparedStatement pStmt = conn.prepareStatement(
"INSERT INTO T1 VALUES(?, ?, ?)");
pStmt.setString(1, emailId);
pStmt.setString(2, gtse);
pStmt.setDate(3, receivedDate);
pStmt.execute();