Java: Using SQLite
First of all you should download SQLite JDBC driver and add it in your project.Next some code manipulations.Here is an example:
import
java.sql.Connection;
import
java.sql.DriverManager;
import
java.sql.PreparedStatement;
import
java.sql.ResultSet;
import
java.sql.Statement;
public
class
main {
private
static
Connection con;
public
void
run()
throws
Exception {
//sqlite driver
Class.forName(
"org.sqlite.JDBC"
);
//database path, if it's new database, it will be created in project folder
con = DriverManager.getConnection(
"jdbc:sqlite:mydb.db"
);
Statement stat = con.createStatement();
stat.executeUpdate(
"drop table if exists weights"
);
//creating table
stat.executeUpdate(
"create table weights(id integer,"
+
"firstName varchar(30),"
+
"age INT,"
+
"sex varchar(15),"
+
"weight INT,"
+
"height INT,"
+
"idealweight INT, primary key (id));"
);
PreparedStatement prep = con
.prepareStatement(
"insert into weights values(?,?,?,?,?,?,?);"
);
prep.setString(
2
,
"vasea"
);
prep.setString(
3
,
"21"
);
prep.setString(
4
,
"male"
);
prep.setString(
5
,
"77"
);
prep.setString(
6
,
"185"
);
prep.setString(
7
,
"76"
);
prep.execute();
//getting data
ResultSet res = stat.executeQuery(
"select * from weights"
);
while
(res.next()) {
System.out.println(res.getString(
"id"
) +
" "
+ res.getString(
"age"
)
+
" "
+ res.getString(
"firstName"
) +
" "
+ res.getString(
"sex"
) +
" "
+ res.getString(
"weight"
)
+
" "
+ res.getString(
"height"
) +
" "
+ res.getString(
"idealweight"
));
}
}
/**
* @param args
*/
public
static
void
main(String[] args) {
try
{
new
main().run();
}
catch
(Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
No comments:
Post a Comment