Java--SQLite 查询 select 查询结果


首先下载Sqlite JDBC驱动程序

网站

https://bitbucket.org/xerial/sqlite-jdbc/downloads/


添加到java 工程lib 库里


package SqliteJDBC;

import java.sql.*;


public class SqliteJDBC {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
	    Connection c = null;
	    try {
	      Class.forName("org.sqlite.JDBC");
	      c = DriverManager.getConnection("jdbc:sqlite:test.db");
	      Statement stmt = null;
	      c.setAutoCommit(false);
	      
	      stmt = c.createStatement();
	      ResultSet rs = stmt.executeQuery( "SELECT * FROM mytable;" );
	      while ( rs.next() ) {
	         int id = rs.getInt("id");
	         String  name = rs.getString("name");
	         int age  = rs.getInt("age");

	         System.out.println( "ID = " + id );
	         System.out.println( "NAME = " + name );
	         System.out.println( "AGE = " + age );
	         System.out.println();
	      }
	      rs.close();
	      stmt.close();
	      c.close();
	    } catch ( Exception e ) {
	      System.err.println( e.getClass().getName() + ": " + e.getMessage() );
	      System.exit(0);
	    }
	    System.out.println("Opened database successfully");
	  

	}

}


创建表:

stmt = c.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);
      stmt.close();
      c.close();


插入数据:

stmt = c.createStatement();
      String sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " +
                   "VALUES (1, 'Paul', 32, 'California', 20000.00 );"; 
      stmt.executeUpdate(sql);


查询结果获取:

在Java中,获得ResultSet的总行数的方法有以下几种。

第一种:利用ResultSet的getRow方法来获得ResultSet的总行数

Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE); 
ResultSet rset = stmt.executeQuery("select * from yourTableName"); 
rset.last(); 
int rowCount = rset.getRow(); //获得ResultSet的总行数

第二种:利用循环ResultSet的元素来获得ResultSet的总行数

ResultSet rset = stmt.executeQuery("select * from yourTableName"); 
int rowCount = 0; 
while(rset.next()) { 
  rowCount++; 
}

rowCount就是ResultSet的总行数。

第三种:利用sql语句中的count函数获得ResultSet的总行数

ResultSet rset = stmt.executeQuery("select count(*) totalCount from yourTableName"); 
int rowCount = 0; 
if(rset.next()) { 
  rowCount=rset .getInt("totalCount "); 
}

rowCount就是ResultSet的总行数


查询列数和每列名:

ResultSet rs = stmt.executeQuery(sql);
			ResultSetMetaData rsmd=rs.getMetaData();
			
			int total = rsmd.getColumnCount();
			System.out.println(rsmd.getColumnTypeName(1));


你可能感兴趣的:(Java)