I'm creating a website for the first time all by myself. I'm doing the logic in Java (I use Ubuntu), and I have written the SQL script for the data base on windows using pgAdmin3 (postgresql).
How do I connect my java program to its database?
If its just java and mysql, then you can try something like this
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/databaseName", "username","password");
As in the example below
public boolean isIdInDb(String id) throws SQLException{
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/databaseName", "username","password");
String rawInfoDb = "select user_id from users ";
Statement statement = conn.createStatement();
ResultSet rSet = statement.executeQuery(rawInfoDb);
boolean isIt = false;
while(rSet.next()){
if(id.equals(rSet.getString(1))){
isIt = true;
}
}
return isIt;
}
Related
I am trying to understand why I can not search more than one record in a database with Java. It is a Java jsp application but I seems to struggle to figure out where the issue is. I am a beginner with jsp but I am sure would not make any difference
try{
String myDriver = "org.gjt.mm.mysql.Driver";//db driver
String myUrl = database;//connect to db
Class.forName(myDriver);
Connection conn = DriverManager.getConnection(myUrl, user, password);//authenticating on database
String query = "SELECT Cus_ID, Cus_name, Cus_surname, Cus_mail, Cus_Address, Cus_telephone FROM customerdb";//mysql select statement
PreparedStatement sta = conn.prepareStatement(query); //prepared statement
ResultSet rst = sta.executeQuery(query);
while (rst.next())
{
String cusid = rst.getString("Cus_ID"); //variable to retrieve the customer from the database
String cusn = rst.getString("Cus_name");
String cussn = rst.getString("Cus_surname");
String cusm = rst.getString("Cus_mail");
String cusaddr = rst.getString("Cus_Address");
String custel = rst.getString("Cus_telephone");
if(!(customer.equals(cusid))){
request.setAttribute("al", "user not found");
request.getRequestDispatcher("account.jsp").forward(request, response); //and user will stay on login page
}if(customer.equals(cusid)){
System.out.println("hello" + cusid);
request.setAttribute("ID", cusid);
request.setAttribute("name", cusn);
request.setAttribute("surname", cussn);
request.setAttribute("mail", cusm);
request.setAttribute("address", cusaddr);
request.setAttribute("telephone", custel);
request.getRequestDispatcher("account.jsp").forward(request, response);
}else{
}
}
}catch(ClassNotFoundException | SQLException | HeadlessException ex) {
Logger.getLogger(LogInController.class.getName()).log(Level.SEVERE, null, ex);
}
The PreparedStatement#executeQuery() method does not take any parameters. Change this:
ResultSet rst = sta.executeQuery(query);
to this:
ResultSet rst = sta.executeQuery();
This is a somewhat common mistake when using this API. You may have other issues with your code as well, but this should make a noticeable improvement.
I have two SQL server running on two different location having same structure but different IP a = 100.0.0.1 and IP b = 192.0.0.1. I have a table a.table and b.table of same structure. Now i want to move all data that is in a. Table from 100.0.0.1 machine to b.table machine 192.0.0.1 .I want to transfer this data using java either connection or by hibernate. Currently i am doing this manually by running SQL query.
Here is the code you can use
import java.sql.*;
import java.io.*;
import java.util.*;
public class test1
{
public static void main(String[] argv) throws Exception
{
try
{
Connection con = DriverManager.getConnection( "jdbc:postgresql://localhost:5432/old","user","pass");
Connection con1 = DriverManager.getConnection( "jdbc:postgresql://localhost:5432/new","user","pass");
String sql = "INSERT INTO users("+ "name,"+ "active,"+ "login,"+ "password)"+ "VALUES(?,?,?,?)";
Statement statement = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
PreparedStatement pstmt = con1.prepareStatement(sql);
ResultSet rs = statement.executeQuery("SELECT * FROM users");
while ( rs.next() )
{
String nm = rs.getString(2);
Boolean ac = rs.getBoolean(3);
String log = rs.getString(4);
String pass = rs.getString(5);
pstmt.setString(1, nm);
pstmt.setBoolean(2, ac);
pstmt.setString(3, log);
pstmt.setString(4, pass);
pstmt.executeUpdate();
}
con.close();
con1.close();
}
catch (SQLException e)
{
System.out.println("could not get JDBC connection: " +e);
}
}
}
Create a connection with something like this
Connection con=DriverManager.getConnection(url, dbProperties);
//then create a query
String query = "select * from a.table";
Statement statement = connect.createStatement(query);
save result in resultset or somewhere else : ResultSet rs = statement.executeQuery(); then create a second connection to your other database like above and call an insert for each result in your resultset. there might be much better methods to insert so much data. i hear about bulk operations but i don't know how they work
If I am using the below code query the database, where would I find the log file for the process? I am looking for what is being sent to the database. The query works from SQL Server Management Studio. The database is MS-SQL 2008.
try{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
String userName = "dbuser";
String password = "dbpswd";
String url = "jdbc:jtds:sqlserver://server:1043"+";databaseName=databasename";
Connection con = DriverManager.getConnection(url,userName,password);
Statement stm = con.createStatement();
ResultSet rs = stm.executeQuery
("SELECT users.id,users.role FROM users WHERE users.username = 'xusername' AND users.password = 'xpswd' AND users.active = 1");
}
When the code runs it returns
'No current row in the ResultSet.'
If I use
System.out.println(stm);
it returns
net.sourceforge.jtds.jdbc.JtdsStatement#7fd2c698
You have to use
rs.next()
to retrieve the first entry. A ResultSet cursor is initially positioned before the first row.
I am having a problem in executing a simple select statement in Microsoft Sql Server DB using a Java program. I am facing below 2 issues,
Code by using statement * Resultset - program just hungs near the executequery() method and no progress after that.
Sample code:-(Full code pasted below)
Statement sta = conn.createStatement();
String Sql3 = "select name from dbo.network";
sta.executeQuery(Sql3);
ResultSet rs=sta.getResultSet();
code with preparestatment * Resultset throws error saying
The method executeQuery() cannot take arguments on a PreparedStatement or CallableStatement
Sample Code:-
PreparedStatement ps = conn.prepareStatement(Sql3);
ResultSet rs = ps.executeQuery(Sql3);
Complete Code:-
public class DbConnectionTest {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
System.out.println("Entered into main method");
String userName ="***";
String password ="***";
String url ="jdbc:sqlserver://****:1433;databaseName=***";
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(url, userName, password);
System.out.println("test");
Statement sta = conn.createStatement();
String Sql3 = "select name from dbo.network";
//PreparedStatement ps = conn.prepareStatement(Sql3);
//ResultSet rs = ps.executeQuery(Sql3);
sta.executeQuery(Sql3);
//sta.getMoreResults();
//sta.getMoreResults();
ResultSet rs=sta.getResultSet();
if(rs != null)
while (rs.next()) {
System.out.println(rs.getString("name"));
}
}catch(Exception se){
//Handle errors for JDBC
se.printStackTrace();
}
}
}
In Addition, I confirm the below,
Same query executes fine in the database.
SQL Browser Server service is running fine
TCP/IP is enabled
Credentials and the URL string are correct
sqljdbc4.jar is used.
Please help me with this issue.
The title is the error I'm getting, when I click load my program freezes. I assume it's because I'm doing a statement inside a statement, but from what I see it's the only solution to my issue. By loading, I want to just repopulate the list of patients, but to do so I need to do their conditions also. The code works, the bottom method is what I'm trying to fix. I think the issue is that I have 2 statements open but I am not sure.
load:
public void DatabaseLoad()
{
try
{
String Name = "Wayne";
String Pass= "Wayne";
String Host = "jdbc:derby://localhost:1527/Patients";
Connection con = DriverManager.getConnection( Host,Name, Pass);
PatientList.clear();
Statement stmt8 = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String SQL8 = "SELECT * FROM PATIENTS";
ResultSet rs8 = stmt8.executeQuery( SQL8 );
ArrayList<PatientCondition> PatientConditions1 = new ArrayList();
while(rs8.next())
{
PatientConditions1 = LoadPatientConditions();
}
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String SQL = "SELECT * FROM PATIENTS";
ResultSet rs = stmt.executeQuery( SQL );
while(rs.next())
{
int id = (rs.getInt("ID"));
String name = (rs.getString("NAME"));
int age = (rs.getInt("AGE"));
String address = (rs.getString("ADDRESS"));
String sex = (rs.getString("SEX"));
String phone = (rs.getString("PHONE"));
Patient p = new Patient(id, name, age, address, sex, phone,
PatientConditions1);
PatientList.add(p);
}
UpdateTable();
UpdateAllViews();
DefaultListModel PatientListModel = new DefaultListModel();
for (Patient s : PatientList) {
PatientListModel.addElement(s.getAccountNumber() + "-" + s.getName());
}
PatientJList.setModel(PatientListModel);
}
catch(SQLException err)
{
System.out.println(err.getMessage());
}
}
This is the method that returns the ArrayList of patient conditions
public ArrayList LoadPatientConditions()
{
ArrayList<PatientCondition> PatientConditionsTemp = new ArrayList();
try
{
String Name = "Wayne";
String Pass= "Wayne";
String Host = "jdbc:derby://localhost:1527/Patients";
Connection con = DriverManager.getConnection( Host,Name, Pass);
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String SQL = "SELECT * FROM PATIENTCONDITIONS";
ResultSet rs5 = stmt.executeQuery( SQL );
int e = 0;
while(rs5.next())
{
e++;
String ConName = (rs5.getString("CONDITION"));
PatientCondition k = new PatientCondition(e,ConName);
PatientConditionsTemp.add(k);
}
}
catch(SQLException err)
{
System.out.println(err.getMessage());
}
return PatientConditionsTemp;
}
I had a similar problem.
I was connecting to derby db hosted on local server.
I created 2 simultaneous connections:
With squirrel
With ij tool
When a connection makes a modification on a table, it first gets a lock for the particular table.
This lock is released by the connection only after committing the transaction.
Thus if the second connection tries to read/write the same table, a msg prompts saying:
ERROR 40XL1: A lock could not be obtained within the time requested
To fix this, the connection which modified the table has to commit its transaction.
Hope this helps !
Here is a good place to start: http://wiki.apache.org/db-derby/LockDebugging
You need to close your statement and result set as well so that when you restart your program they won't be open. Add stmt.close(); and rs.close(); at the end of your lines of code within the try and catch statement.
Why could you not use the same connection object to do both the queries?
Like pass that connection object to the LoadPatientConditions() as a parameter and use it there.