Java操作数据库Sqlite样例代码
生活随笔
收集整理的這篇文章主要介紹了
Java操作数据库Sqlite样例代码
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
Java對數(shù)據(jù)的操作需要通過JDBC中間件,需要先配置好sqlite-jdbc-(版本號).jar。
JDBC學(xué)習(xí)教程可參考:http://www.runoob.com/w3cnote/jdbc-use-guide.html
Sqlite教程JAVA部分教程:http://www.runoob.com/sqlite/sqlite-java.html
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement;public class SqliteJDBC {public static void main(String[] args) {Connection cnt = null;try {// 加載驅(qū)動程序Class.forName("org.sqlite.JDBC");// 創(chuàng)建連接對象cnt = DriverManager.getConnection("jdbc:sqlite:test.db");System.out.println("Opened database successfully.");// 創(chuàng)建會話狀態(tài)Statement stmt = cnt.createStatement();// 建表?String sql = "CREATE TABLE COMPANY "+"(ID INT PRIMARY KEY NOT NULL, "+"NAME TEXT NOT NULL, "+"AGE INT NOT NULL, "+"ADDRESS CHAR(50), "+"SALARY REAL);";stmt.executeUpdate(sql);System.out.println("create table successfully.");// 填入數(shù)據(jù)sql = "INSERT INTO COMPANY (ID, NAME, AGE, ADDRESS, SALARY) "+ "VALUES (1, 'Paul', 32, 'California', 20000.00);";stmt.executeUpdate(sql);sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " + "VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 );";?stmt.executeUpdate(sql);System.out.println("fill data successfully.");// 數(shù)據(jù)查詢Query(stmt);// 更新數(shù)據(jù)操作sql = "UPDATE COMPANY set SALARY = 25000.00 where ID=1;";stmt.executeUpdate(sql);System.out.println("update successfully.");Query(stmt);// 刪除數(shù)據(jù)操作sql = "DELETE from COMPANY where ID=4;";stmt.executeUpdate(sql);System.out.println("delete successfully.");Query(stmt);// 關(guān)閉聲明,及連接stmt.close();cnt.close();}catch(Exception e){System.err.println(e.getClass().getName() + ":" + e.getMessage());System.exit(0);}}// 單獨(dú)創(chuàng)建查詢功能模塊public static void Query(Statement stmt) throws SQLException{String sql = "SELECT * FROM COMPANY;";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");float Salary = rs.getFloat("SALARY");System.out.println( "ID = " + ID );System.out.println( "NAME = " + Name );System.out.println( "AGE = " + Age );System.out.println( "ADDRESS = " + Address );System.out.println( "SALARY = " + Salary );System.out.println();}rs.close();} }?
?
總結(jié)
以上是生活随笔為你收集整理的Java操作数据库Sqlite样例代码的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 将 Windows10 中的 WSL 添
- 下一篇: JAVA网络编程之Socket