Current location - Education and Training Encyclopedia - Graduation thesis - How to insert data into database with java (how to import database with java)
How to insert data into database with java (how to import database with java)
The Java program inserts data into the database, and the code is as follows:

//First create a database (aess, oracle, mysql, SQL server), in which AESS aess and SQL server need to be configured with data source (ODBC);

//Then create the class (ConnDb, Test, TestBean)ConnDb eclipse. Conndb function is a class that connects to database, queries, inserts, deletes and modifies data. Test is a test class that contains the main method, and TestBean is a field property, which is the set and get methods in the data table.

//Here is the ConnDb code:

packagedb

import Java . SQL . connection;

importjava.sql

Imported?

Java . SQL . resultset;

importjava.sql

Imported?

Java.sql. statement;

import Java . util . ArrayList;

publicsclassconndb {

publicConnectionstartConn(connection conn){

Try {

class . forname(" sun . JDBC . odbc . ");

Connection =. ("jdbc:odbc: database", "user name" and "password");

} catch(exception one){

System.out.println ("Error connecting to database");

}

returnconn

}

publicArrayList(Stringsql){

Connectionconn = null

Statementstmt = null

ResultSetrs = null

ArrayList list = new ArrayList();

Try {

conn = start conn(conn);

stmt = conn .();

rs=stmt。 (SQL); //sql is an sql statement, such as "select*from"

Table name ",passed in from the main method, in which the ArrayList class is used to store the query results.

while(rs.next()){

testbean TB = new testbean();

TB . settid(RS . getstring(" tid "));

TB . set name(RS . getstring(" tname "));

TB . setinfo(RS . getstring(" tinfo "));

list . add(TB);

}

}

Capture (e)

//TODOAuto-generatedcatchblock

e.();

} Finally {

closeConn(rs,stmt,conn);

}

returnlist

}

publicvoid(Stringsql){

Connectionconn = null

Statementstmt = null

Try {

Connection =

StartConn (Kang En);

stmt = conn .();

stmt。 (SQL);

}

Capture (e)

System.out.println ("Error in modifying, inserting or deleting database data!" );

} Finally {

CloseConn (stmt, Connecticut);

}

}

publicvidcloseconn(ResultSetrs,Statementstmt,Connectionconn){

Try {

If (rs! =

null){

RS . close();

}

If (stmt! =null){

stmt . close();

}

If (conn! =null){

conn . close();

}

}

Capture (e)

//TODOAuto-generatedcatch

block

System.out.println ("Error closing database!" );

}

}

publicvidcloseconn(Statementstmt,Connectionconn){

Try {

If (stmt! =null){

stmt . close();

}

If (conn! =null){

conn . close();

}

}

Capture (e)

//TODOAuto-generatedcatchblock

System.out.println ("Error closing database!" );

}

}

}