Print SQL table with java - java

I cant print SQL table with JAVA. I think JDBC Connection is not a problem. How can I print table in console??
Connection conn = null;
Statement stmt = null;
String url = "jdbc:oracle:thin:#localhost:1521:orcl";
String user = "system";
String pwd = "SSTTaarr00119922";
ResultSet rs = null;
I did drivermanager getconnection.
System.out.println("start Connection");
try {
Class.forName("oracle.jdbc.OracleDriver");
conn = DriverManager.getConnection(url, user, pwd);
} catch (ClassNotFoundException e1) {
System.out.println("Error loading driver:" + e1.toString());
return;
} catch (Exception e2) {
System.out.println("Fail DB Connection:" + e2.toString());
return;
}
String sql = "SELECT * FROM dept";
try {
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
System.out.println(sql);
while (rs.next()) {
String deptno = rs.getString(1);
String dname = rs.getString(2);
String Loc = rs.getString(3);
System.out.println(deptno + dname + Loc);
}
I cant print while func.

In your code, you are missing the catch in try---catch block. The code below is worked with SQL Server
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
System.out.println("start Connection");
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection("jdbc:sqlserver://localhost;databaseName=xxx;", "yyy", "zzz");
} catch (ClassNotFoundException e1) {
System.out.println("Error loading driver:" + e1.toString());
return;
} catch (Exception e2) {
System.out.println("Fail DB Connection:" + e2.toString());
return;
}
String sql = "SELECT * FROM [dbo].[User]";
try {
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
System.out.println(sql);
while (rs.next()) {
String deptno = rs.getString(1);
String dname = rs.getString(2);
String Loc = rs.getString(3);
System.out.println(deptno + dname + Loc);
}
} catch (Exception e2) {
System.out.println("Fail DB Connection:" + e2.toString());
}

Related

Saving a file in postgres database using native query

I am trying to save a file in the database. I am able to save using SQL it works perfectly fine. What I am avoiding with SQL is providing password directly in the code that why I am considering using native query. I am unsure if I can still use SQL without providing password and username directly in the code.The code for the SQL is as below
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Connection connection = null;
try {
connection = DriverManager.getConnection(
"jdbc:postgresql://localhost:5432/mydb", "postgres",
"postgres");
System.out.println("......Now attempting to insert the record.....");
// String matid = "007N00030000001";
File file = new File("C://JavaWorkspace/pdf-sample.pdf");
FileInputStream fis = new FileInputStream(file);
PreparedStatement ps = connection.prepareStatement("INSERT INTO cli.documents VALUES (?,?,?,?)");
ps.setBinaryStream(1, fis, (int)file.length());
ps.setString(2, "1");
ps.setString(3, file.getName());
ps.setString(4,matid);
ps.executeUpdate();
ps.close();
fis.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
If using native query I cant see any method that I can use instead of
ps.setBinaryStream(1, fis, (int)file.length());
there is only setParameter
below is my attempt using native query
Query query = entityManager.createNativeQuery("INSERT INTO cli.documents (matid, doctype,upload,docfile) " +
" VALUES(?,?,?,?)");
EntityManagerFactory emfactory=Persistence.createEntityManagerFactory( "junit" );
EntityManager em = emfactory.createEntityManager( ); //= null;
EntityTransaction et = em.getTransaction();
et.begin();
em.createNativeQuery("INSERT INTO cli.documents (matid, doctype,upload,docfile) " + " VALUES(?,?,?,?)")
.setParameter(1,matid)
.setParameter(2, "1")
.setParameter(3, file.getName())
.setParameter(4, (int)file.length());
//.setBinaryStream(4, fis, (int)file.length())
// em.executeUpdate()
et.commit();

How to store fetched values from database into a text file

I need your help in storing the fetched values from a database into a text file (Sample.txt). Each fetched row should be stored in the text file and separated by a line break. After each retrieved column it should be separated by a line "|", So I need your help. Here is the code:
public void GenerateTXT() {
Connection conn = null;
Statement stmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
String sql = "SELECT id, name, amount FROM Employee";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
int id = rs.getInt("id");
int age = rs.getString("name");
String first = rs.getInt("amount");
}
rs.close();
}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
}
}
you can use the below code.
public void GenerateTXT() {
Connection conn = null;
Statement stmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
File file = new File("/path/to/file/filename.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
String sql = "SELECT id, name, amount FROM Employee";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
int id = rs.getInt("id");
int age = rs.getString("name");
String first = rs.getInt("amount");
bw.append(id+"|"+age+"|"+first+"\n");
}
rs.close();
bw.close();
}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
}
}

Exception in thread "Thread-0" java.lang.NullPointerExceptionat eece.pkg350.MultiThreadedServer$ServerThread.run

i was writing a client server application in java where the client has certain functions to do and the server should access the data base and send back to the client. the function login will go to the data base and check if that user exists and send the corresponding message from the server to the client. however i keep getting this exception : Exception in thread "Thread-0" java.lang.NullPointerException. how should i solve that? Thank you a lot
here is the code for my server:
public void run()
{
try
{
datain = new BufferedReader(new InputStreamReader(socket.getInputStream()));
dataout = new DataOutputStream(socket.getOutputStream());
}
catch (IOException e)
{
System.out.println("first IOException");
e.printStackTrace();
return;
}
String res = ";";
try
{
String command = datain.readLine();
System.out.println(command);
if("Log In".equals(command)){
String email = datain.readLine();
System.out.println(email);
String password = datain.readLine();
System.out.println(password);
res = jdbc.LogIn(email,password);
/*ServerSxocket s = new ServerSocket(1927);
socket = s.accept();*/
System.out.println(res);
dataout.writeBytes(res + '\n');
//DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
System.out.println("closing socket");
datain.close();
dataout.close();
socket.close();
}
}
catch (IOException e)
{
System.out.println("second IOException");
e.printStackTrace();
}
i have this function that i am using to check if a certain record exists in the database
public String LogIn (String email, String password){
int userCount = 0;
String res = "hey";
String sql = "SELECT COUNT(*) from users WHERE email = '" + email + "'";
String p = "";
Statement command = null;
ResultSet rs = null;
try {
conn = DriverManager.getConnection(DB_URL, USER, PASS);
command = conn.createStatement();
rs = command.executeQuery(sql);
userCount = Integer.parseInt(rs.getString(sql));
if (userCount==1){
res = "There is a user with this account";
}
if (userCount==0){
res = "There is no account with this email";
System.out.println(res);
}
else {
sql = "SELECT password from users WHERE email = '"+email+"'";
rs = command.executeQuery(sql);
p = rs.getString(sql);
if (p==password){
res = "correct password";
}
else {
res = "The password you entered is incorrect";
System.out.println(res);
}
}
}
catch(SQLException s){
s.printStackTrace();
}
return res;
}

Unable to reopen MySQL connection in Java

I've got an annoying bug in Java. I'm connecting to a MySQL database and using Tomcat in Eclipse. It works brilliantly, but only the first time around. If I reload the page or run the page again, I get a com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed.
This is my code:
Connection conn = null;
String returnString = null;
Response response = null;
ResultSet rs = null;
try {
System.out.println("Trying to connect");
conn = DbUtil.getConnection(); // Connect to the database
System.out.println("Okay, connected");
query = conn.prepareStatement("SELECT host_firstname FROM host"); //Crashes at this line!
rs = query.executeQuery();
ConvertToJson jsonConverter = new ConvertToJson();
JSONArray jsonArray = new JSONArray();
jsonArray = jsonConverter.convertToJsonArray(rs);
returnString = jsonArray.toString();
response = Response.ok(returnString).build();
}
catch (Exception e) {
e.printStackTrace();
System.out.println("hello!!!!");
}
finally {
if (rs != null){
rs.close();
}
if (query != null) {
query.close();
}
if (conn != null) {
conn.close();
}
}
return response;
I've seen everywhere I've Googled that I have to close the result set, the prepared statement and the connection (in that order) but once I've closed the connection, I can't reopen it.
This is my DbUtil class:
private static Connection connection = null;
public static Connection getConnection() {
if (connection != null) {
return connection;
}
else {
try {
Properties prop = new Properties();
InputStream inputStream = DbUtil.class.getClassLoader().getResourceAsStream("/db.properties");
prop.load(inputStream);
String driver = prop.getProperty("driver");
String url = prop.getProperty("url");
String user = prop.getProperty("user");
String password = prop.getProperty("password");
Class.forName(driver);
connection = DriverManager.getConnection(url, user, password);
}
catch (IOException e) {
e.printStackTrace();
}
catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return connection;
}
Any idea what is causing this problem?
Thanks
Omar :)
This answer is just to get your code working. But the best way would be to configure a connection pool. You should look about it.
YOur condition is :
if (connection != null) {
return connection; It's returning a closed connection
}
Try changing it to:
if (connection != null && !connection.isClosed()) {
return connection;
}

How to upload file in database?

I am trying to upload an image file with the code below, but the file is not being uploaded. The console still shows the message "1 Record Successfully Inserted."
Create table image
(
name varchar2(20),
photo blob
);
import java.sql.*;
import java.io.*;
public class ImageWriter {
static Connection connection = null;
static CallableStatement pstat = null;
static String connectionURL = null;
public static void main(String[] args) {
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
connection = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe", "SYSTEM", "SYSTEM");
PreparedStatement pstat = connection.prepareStatement("insert into image(name,photo) values(?,?)");
FileInputStream fin = new FileInputStream("E:\\test.jpg");
pstat.setString(1, "ABC");
pstat.setBinaryStream(2, fin,fin.available());
int result = pstat.executeUpdate();
System.out.println(result + " Record Successfully Inserted");
connection.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
The above code works fine.
I dont know how you verified the contents of database.
Here is my code to verify the db(blob column): Try with this method. I used your code to insert the image and I could retrieve the image successfully. (note : file extension should be same)
public static void getPic() {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:orcl", "sys as sysdba",
"Oracle123");
ResultSet rs = null;
Statement stmt = null;
oracle.sql.BLOB photo = null;
conn.setAutoCommit(false);
stmt = conn.createStatement();
String name="ABC";
rs = stmt.executeQuery("select photo from image where name = '" + name + "'" );
rs.next();
photo = ((OracleResultSet) rs).getBLOB(1);
File f = new File("E:/image2.jpg");
f.getParentFile().mkdirs();
f.createNewFile();
InputStream in = photo.getBinaryStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
OutputStream outputStream = new FileOutputStream(f);
int bufferSize = 1024;
int length = (int) photo.length();
byte[] buffer = new byte[bufferSize];
while((length = in.read(buffer)) != -1) {
out.write(buffer,0,length);
}
out.writeTo(outputStream);
System.out.println("Image Retrieved");
out.close();
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}

Categories

Resources