1.有两个表,表的属性都有:id,name,sex,age;第一个表有700条数据,第二个表有500条数据,其中两个表中有300条是name相同的,如何把两个表中不相同的数据取出来,怎么做?
答:
首先建2个表student1和student2,各有以上的四个字段。
我用mysql5.1数据库测试
1.SELECT DISTINCT t.* FROM (SELECT * FROM student1 UNION (SELECT * FROM student2 )) AS t
2.SELECT * FROM student1 UNION (SELECT * FROM student2 WHERE NAME NOT IN (SELECT NAME FROM student1))
以上两个sql都可以查到。
数据库连接
package com.db; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.Properties; import com.mysql.jdbc.PreparedStatement; public class DBConnection { //从db.properties获取属性然后使用 public String[] getDBProperties(String dbtype){ Properties prop=new Properties(); String driver = null,url=null,username=null,password=null; try { String type=changDBType(dbtype); String[] dbCon=new String[]{ type+"_Driver", type+"_Url", type+"_Username", type+"_Password"}; prop.load(ClassLoader.getSystemResourceAsStream("db.properties")); driver=prop.getProperty(dbCon[0]); url=prop.getProperty(dbCon[1]); username=prop.getProperty(dbCon[2]); password=prop.getProperty(dbCon[3]); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } String db[]=new String[]{driver,url,username,password}; return db; } //首先把字符串的第一个字符变大写,其他的变小写 public String changDBType(String dbtype) throws Exception{ if(dbtype.isEmpty()){ throw new Exception("dbtype字符串为空"); }else{ return String.valueOf(dbtype.charAt(0)).toUpperCase().concat(dbtype.substring(1).toLowerCase()); } } Connection con; Statement stat; public Connection getCon(String driver,String url,String username,String password){ try{ Class.forName(driver); con=DriverManager.getConnection(url,username,password); stat=con.createStatement(); }catch(SQLException e){ System.out.println("数据库连接SQL异常"); } catch (ClassNotFoundException e) { System.out.println("数据库连接类找不到异常"); e.printStackTrace(); } return con; } public static void main(String args[]){ DBConnection dbc=new DBConnection(); String db[]=dbc.getDBProperties("mysql"); Connection con=dbc.getCon(db[0], db[1], db[2], db[3]); String sql1="insert into student1(id,name,sex,age) values(?,?,?,?)"; String sql2="insert into student2(id,name,sex,age) values(?,?,?,?)"; try { PreparedStatement pstmt=(PreparedStatement) con.prepareStatement(sql2); for(int i=301;i<=500;i++){ pstmt.setObject(1, i); pstmt.setObject(2, "郑爽"+i); pstmt.setObject(3, "女"+i); pstmt.setObject(4, 20); pstmt.execute(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
db.properties
Mysql_Driver=com.mysql.jdbc.Driver Mysql_Url=jdbc:mysql://localhost:3306/itcast?useUnicode=true&characterEncoding=UTF-8 Mysql_Username=root Mysql_Password=liming Oracle_Driver=oracle.jdbc.driver.OracleDriver Oracle_Url=jdbc:oracle:thin:@127.0.0.1:1521:orcl Oracle_Username=ytpms Oracle_Password=ytpms