myeclips 数据库查询,用户增加数据代码

查询数据库中的数据

 

package jdbc;
import java.io.*; 
import java.util.*;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class select {

 public static void main(String[] args)  {
  jdbc();
   }
 static void jdbc() 
 {
  
  try{
   Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
   System.out.println("加载驱动成功");
   String url="jdbc:sqlserver://localhost:1433;DatabaseName=GreenHome";
    Connection conn=DriverManager.getConnection(url, "sa", "sa");
   System.out.println("连接成功:");
   String sql="select * from persons";                                            //查询persons表中全部的数据
   Statement stmt=conn.createStatement();
   ResultSet rs= stmt.executeQuery(sql);
   while(rs.next())                                                                             //循环遍历
   {
    int id=rs.getInt(1);
    String name=rs.getString(2);
    String password=rs.getString(3);
    int sex=rs.getInt(4);
    String Email=rs.getString(5);
    System.out.println(id+" "+name+" "+password+" "+sex+" "+Email);                      //输出查询结果
   }
   stmt.close();
         conn.close();
   }
   catch (ClassNotFoundException e) {
    e.printStackTrace();
  } catch (SQLException e) {
     e.printStackTrace();
  }
    }}

 用户添加数据插入数据库

package jdbc;
import java.io.*; 
import java.util.*;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class insertdata {

 public static void main(String[] args) throws ClassNotFoundException, SQLException   {

//输入要插入数据表中的数据
  System.out.println("name");
  String name=sql();
  System.out.println("password");
  String password=sql();
  System.out.println("sex");
  String sex=sql();
  System.out.println("email");
  String email=sql();
  insert(name,password,sex,email);
 }
   static void insert(String name,String password,String sex,String email) throws ClassNotFoundException, SQLException 

 {       
     String sql="insert into mayuan(name,password,sex,Email)values(?,?,?,?)";
   Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
   System.out.println("加载驱动成功");
   String url="jdbc:sqlserver://localhost:1433;DatabaseName=GreenHome";
    Connection conn=DriverManager.getConnection(url, "sa", "123");
   System.out.println("连接成功:");
   PreparedStatement psmt=null; 
   try{
   PreparedStatement stmt=conn.prepareStatement(sql);                         
   stmt.setString(1, name);
   stmt.setString(2, password);
   stmt.setString(3, sex);
   stmt.setString(4, email);
   stmt.executeUpdate();
   System.out.print("ok");
   stmt.close();
         conn.close();
   }
   
   catch (SQLException e) {
   e.printStackTrace();
  }
 }
 static String sql()
 {
  Scanner input= new Scanner(System.in);
  String sql=input.nextLine();
  return sql;
 }
}

 

你可能感兴趣的:(数据库)