updating a record at runtime using jdbc - jdbc

I have problem updating my password at runtime.
It gives no error but it just doesn't work.
Please help .
Thanks in Advance!
Here is my code:
//HERE IS THE PROBLEM PART WHICH IS NOT WORKING
try {
System.out.println("id is : "+j);
System.out.println("What do you want your new password to be?");
Scanner s8=new Scanner(System.in);
String s7=s8.nextLine();
Class.forName("com.mysql.jdbc.Driver");
Connection con5=DriverManager.getConnection("jdbc:mysql://localhost:3306/login","root","q");
PreparedStatement ps=con5.prepareStatement("update pass set password=? where id=?");
ps.setString(1,s7);
ps.setInt(2,j);
}
catch(Exception e)
{
System.out.println(e);
}

You miss the execution of your statement using PreparedStatement.executeUpdate().
From javadoc
Executes the SQL statement in this PreparedStatement object, which
must be an SQL Data Manipulation Language (DML) statement, such as
INSERT, UPDATE or DELETE; or an SQL statement that returns nothing,
such as a DDL statement.

Related

Query Oracle using .net core throws exception for Connect Identifier

I'm quite new to Oracle and never used that before, now, I'm trying to query an Oracle database from a .Net Core Web Application having nuget package oracle.manageddataaccess.core installed and using an alias as the Data Source but I'm receiving the following error:
If I use the full connection string the query will work correctly
ORA-12154: TNS:could not resolve the connect identifier specified
at OracleInternal.Network.AddressResolution..ctor(String TNSAlias, SqlNetOraConfig SNOConfig, Hashtable ObTnsHT, String instanceName, ConnectionOption CO)
at OracleInternal.Network.OracleCommunication.Resolve(String tnsAlias, ConnectionOption& CO)
at OracleInternal.ConnectionPool.PoolManager`3.ResolveTnsAlias(ConnectionString cs, Object OC)
at OracleInternal.ServiceObjects.OracleConnectionImpl.Connect(ConnectionString cs, Boolean bOpenEndUserSession, OracleConnection connRefForCriteria, String instanceName)
So, from a few links I could understand that there is a tsnnames.ora file which must contain the map between connect identifiers and connect descriptors. And that this file can be found at the machine on which the Oracle has been installed with the path ORACLE_HOME\network\admin.
Question is:
Does the alias name that I'm using in my connection string which reads as Data Source: <alias_name>; User ID=<user>; Password=<password> need to be specified in the tsnnames.ora file? I don't have access to the machine where the Oracle database resides on otherwise I would have checked it earlier.
Here's the code snippet for more info: connection string and query values are mocked out
public static string Read()
{
const string connectionString = "Data Source=TestData;User ID=User1;Password=Pass1";
const string query = "select xyz from myTable";
string result;
using (var connection = new OracleConnection(connectionString))
{
try
{
connection.Open();
var command = new OracleCommand(query) { Connection = connection, CommandType = CommandType.Text };
OracleDataReader reader = command.ExecuteReader();
reader.Read();
result = reader.GetString(0);
}
catch (Exception exception)
{
Console.WriteLine(exception);
throw;
}
}
return result;
}
Is this enough or something else needs to be added/changed in here? Or probably the issue is with the tsnNames.ora file which might not contain the alias name here?
Thanks in advance
For the Data source
Data Source=TestData;User Id=myUsername;Password=myPassword;
Your tnsnames.ora probably should have the below entry
TestData=(DESCRIPTION=
(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=MyHost) (PORT=MyPort)))
(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=MyOracleSID)))
Since
Data Source=TestData;User Id=myUsername;Password=myPassword;
is same as
Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=MyHost) (PORT=MyPort)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=MyOracleSID)));User Id=myUsername;Password=myPassword;

is it possible to do batch updates to the clickhouse using clickhouse-jdbc driver?

I'm trying to do a batch update of data to one of the tables in clickhouse database. I use such driver:
<dependency>
<groupId>ru.yandex.clickhouse</groupId>
<artifactId>clickhouse-jdbc</artifactId>
<version>0.1.52</version>
</dependency>
The thing is when i update a table using next instruction:
jdbcTemplate.batchUpdate(str)
I have an empty array as a response and there's no records in the database. There's no exceptions also.
Does it mean that the driver is not ready for batch updates? Is there any workarounds?
thanks in advance!
Clickhouse jdbc driver support batch updates. In plain jdbc code this will look like this:
try (Connection connection = dataSource.getConnection();
PreparedStatement ps = connection.prepareStatement(query)) {
for (Data data : datas) {
ps.setInt(1, data.id);
ps.addBatch();
}
ps.executeBatch();
connection.commit();
} catch (Exception e) {
....
}

Configure Datasource with timezone in jboss/weblogic server

I am going to handle multiple time zone in my web application by resetting database session time zone every time getting DB connection.
The code looks like:
public Connection getConnection(GmDNSNamesEnum enDNSName) throws AppError
{
...
DataSource ds = (DataSource) ic.lookup(enDNSName.getDNSName());
conn = ds.getConnection();
conn.setAutoCommit(false);
setTimeZone(strTimeZone);
...
return conn;
}
private void setTimeZone(String strTimeZone){
Statement stmt = null;
if(conn != null) {
try{
stmt = conn.createStatement();
stmt.execute("alter session set time_zone=\'" + strTimeZone+"\'");
} catch (Exception e)
{
String strErrorMsg = GmCommonClass.getExceptionStackTrace(e);
log.error("Exception e "+strErrorMsg);
throw new AppError(e);
}
}
}
Is there any alternate way to set database session time zone?
now, I am looking for configure datasource with different timezone in jboss/weblogic server and use appropriate datasource specific to user timezone instead of every time reset the session time zone by executing alter session script.
thanks in advance
Wow ok.
Perhaps you could try persisting the dates and times into timezone-aware database columns instead of contorting the data source each time you connect? The convention is to store dates in UTC time, then do timezone conversion in the presentation layer (or at least post-retrieval).

login page automatically redirects to else case

this code shud check login credentials and forward either to logged in page for admin when getParameter(7)=1 or to customer when it is 0..
if login credentials are not correct it will go to error messages and fromt her to login page again.. but somehow it is directly going to errorpage in else case if its not admin!! next two cases are not being checked at all!!
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mutualfund", "root", "");
Statement stmt = con.createStatement();
ResultSet result = stmt.executeQuery("SELECT * FROM login_table;");
String uname= request.getParameter("username");
String pass= request.getParameter("password");
while(result.next())
{
if(result.getString(1).equals(uname) && result.getString(2).equals(pass))
{
if(result.getBoolean(7)==true)
{
response.sendRedirect("displayFunds.jsp");
}
if((result.getBoolean(7)==false) && (result.getString(4).equals("")))
{
response.sendRedirect("changePassword.jsp?name="+uname+"&&pass="+pass);
}
if((result.getBoolean(7)==false) && (!result.getString(4).equals("")))
{
response.sendRedirect("custProfile.jsp");
}
}
else
{
response.sendRedirect("loginFailed.jsp");
}
}
}
catch (Exception ex) {
Logger.getLogger(Admin.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
You're not returning from the method, but continuing to iterate through the while loop. You seem to expect that a simple method call response.sendRedirect() magically aborts the whole while loop and returns from the method. It doesn't do that. The code just continues the loop, checking the next user and setting the redirect URL, hereby overriding the previous one.
You need to return from the method yourself.
response.sendRedirect(someURL);
return;
Your concrete problem is caused because your login doesn't match the last user entry in the DB.
Unrelated to the concrete problem, this approach is however terribly inefficient. You're not taking benefit of the powers of a relational database and instead copying the entire DB table into Java's memory and performing the comparison in Java. You should be writing SQL queries in such way that it returns exactly the information you need. In this particular case, you should be using the SQL WHERE clause instead (in a prepared statement!), so that the resultset contains exactly zero or one row.
if (resultSet.next()) {
// Login OK!
} else {
// Login fail!
}
Further, your code is also leaking DB resources by never closing them. You should be closing them in finally. Also, loading the JDBC driver on every HTTP request is unnecessary. Just load it once during webapp's/servlet's startup.
See also:
Login works only for last user in the database
JDBC always tests the last row of MySQL table?
How often should Connection, Statement and ResultSet be closed in JDBC?

How to connect to Play Framework in-memory database using JDBC?

I use the in-memory database that comes with Play Framework, when I have db=mem in the configuration file, for development.
How can I connect to this database using JDBC? and not the JPA that is the default way.
I have tried with this method in my controller:
public static void addToDB() {
try {
Connection conn = DriverManager.getConnection("jdbc:h2:mem:play");
Statement stmt = conn.createStatement();
stmt.execute(sql);
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
But I get an error message that I need to provide an username and password:
org.h2.jdbc.JdbcSQLException: Wrong user name or password [8004-149]
If I visit the web-console on /#db the username sa is used and no password.
Now I logged in via the /#db interface and created a table users.
Then I connected to the database in a controller method and used this jdbc-string: jdbc:h2:mem:play:sa and then tried to insert to the table users but I get this error message:
org.h2.jdbc.JdbcSQLException: Table "USERS" not found; SQL statement:
How should I connect to the in-memory H2 database in Play Framework using JDBC?
DB.getConnection(), should do the job.
Try:
Connection conn = DriverManager.getConnection("jdbc:h2:mem:play", "sa", "");
because as you wrote, "the username sa is used and no password."

Resources