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();
}
}
}
}
Related
I have a api executing several requests in mysql,
I launched this method several times, an error message is displayed too many connection, I try to close each time the connection after the execution of query but its not solving my problem
#PostMapping(value="/checkSql")
public ArrayList ExecuteSql(#RequestBody SQLBody sqlBody) {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
ArrayList array = new ArrayList();
DataSource datatsource = dataSource( sqlBody.getUsername(),sqlBody.getPassword(),sqlBody.getUrl(),sqlBody.getDriver());
try {
List<Fonctionnalite> listFonctionalite = findAllMP();
for( Fonctionnalite item : listFonctionalite) {
con = datatsource.getConnection();
stmt = con.createStatement();
FileReader fr=new FileReader("C:\\Users\\jihed\\OneDrive\\Bureau\\versionfinalPfe2020\\f2\\"+item.getName()+"\\"+item.getFileChek());
int i;
StringBuffer sb = new StringBuffer();
while((i=fr.read())!=-1) {
sb.append((char)i);
}
System.out.println(sb);
fr.close();
rs = stmt.executeQuery(sb.toString());
ResponseChek check = new ResponseChek(item.getId(),item.getName(),item.getDesscription(),item.getFileActivation(),item.getFilaDesactivation(),item.getFileChek(),1);
array.add(check);
if(rs != null) rs.close();
if(stmt != null) stmt.close();
if(con != null) con.close();
}
} catch (SQLException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
if(rs != null) rs.close();
if(stmt != null) stmt.close();
if(con != null) con.close();
if(datatsource != null) datatsource = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
return array;
}
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());
}
I am trying to insert data into sqlite table but it is giving me exception no such exception.please check my code and let me what changes should i make?
static Connection con;
public static Connection getConnection()
{
try
{
Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("jdbc:sqlite:/home/zack/another.db");
con.setAutoCommit(false);
System.out.println("Opened database successfully");
}
catch(Exception e)
{
System.out.println("EXCEPTION IN :: SqliteCon:"+e.getMessage());
}
return con;
}
and here is my insert command file.
public String execute()
{
BufferedReader br;
try {
Connection con = SqliteCon.getConnection();
Statement stmt = con.createStatement();
br = new BufferedReader(new FileReader(
"/home/Zack/Desktop/session.csv"));
String line;
while ((line = br.readLine()) != null) {
String[] value = line.split(","); // your seperator
stmt.executeUpdate("INSERT into sessionTab values('jack','pass','NYC'")
//later i will insert values from CSV file
br.close();
}
}
catch (Exception e) {
System.out.println("Exception in UploadData class");
e.printStackTrace();
}
return SUCCESS;
}
I also added jar file to WEB-INF/lib/ of my project
finally solved this issue!!!switched from sqliteman to Firefox sqlite plugin and changed extension of db file from .db to .sqlite.
This mysql script does not work correctly. I tried executing the query to create tables in the phpmyadmin and it worked. The database is created but the table does not get created and I do not get any errors/stack traces.
This is my code
public void createDatabase() {
java.sql.Connection conn = null;
java.sql.Statement stmt = null;
try{
// Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
// Create database
System.out.println("Creating table in given database...");
stmt = conn.createStatement();
String createdatabase = "CREATE DATABASE TimePoints;";
stmt.executeUpdate(createdatabase);
System.out.println("Created the database.");
// Create table
System.out.println("Creating table in given database...");
stmt = conn.createStatement();
String createtable = "CREATE TABLE players (playername VARCHAR(38), playertime BIGINT);";
stmt.executeUpdate(createtable);
System.out.println("Created the table.");
}catch(SQLException se){
// Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
// Handle errors for Class.forName
e.printStackTrace();
}finally{
// Finally block used to close resources
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
} //end finally try
} //end try
System.out.println("Goodbye!");
}
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();
}
}