/*
*
* 功能:用jdbc方法去操作数据库
* 1、把java.sql*;引入
* 2、需要引入四个jar包
* 3、特别说明:如果取值时按编号取值则需要一一对应
* 如果是按照列名来取值,则顺序可以颠倒
*/
package com.test4;
import java.sql.*;
public class Test4 {
public static void main(String[] args) {
//preparedStatement[火箭车]
PreparedStatement ps=null;
Connection ct=null;
ResultSet rs=null;
try{
//加载驱动
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
//得到链接
ct=DriverManager.getConnection("jdbc:microsoft:sqlserver://127.0.0.1:1434;databaseName=test","sa","199303");
//创建火箭车
/*
ps=ct.prepareStatement("select *from emp");
//执行(如果是增加,删除,修改用executeUpdate(),如果是查询用executeQuery())
rs=ps.executeQuery();
//如果查询语句是*号,取数据是应按照数据在数据库表中的所在列的号来取出
while(rs.next())
{
String name=rs.getString(2);
float sal=rs.getFloat(6);
int deptno=rs.getInt(8);
// 也可以列名来取
// String name=rs.getString("ename");
// float sal=rs.getFloat("sal");
// int deptno=rs.getInt("deptno");
System.out.println(name+" "+sal+" "+deptno+" ");
}
*/
//不用*时,应以SQL语句上的顺序来去
/* ps=ct.prepareStatement("select ename,sal,deptno from emp");
rs=ps.executeQuery();
while(rs.next())
{
String name=rs.getString(1);
float sal=rs.getFloat(2);
int deptno=rs.getInt(3);
// 也可以根据列名来取
// String name=rs.getString("ename");
// float sal=rs.getFloat("sal");
// int deptno=rs.getInt("deptno");
System.out.println(name+" "+sal+" "+deptno+" ");
}
*/
//多表查询
/*
ps=ct.prepareStatement("select ename,sal,dname from emp,dept where emp.deptno=dept.deptno");
rs=ps.executeQuery();
while(rs.next())
{
String name=rs.getString(1);
float sal=rs.getFloat(2);
String dname=rs.getString(3);
System.out.println(name+" "+sal+" "+dname+" ");
}
*/
//添加,删除,修改
ps=ct.prepareStatement("insert into dept values(?,?,?)");
ps.setInt(1, 100);
ps.setString(2, "财务部");
ps.setString(3," 大学城");
int i=ps.executeUpdate();
if(i==1)
{
System.out.println("ok");
}else
{
System.out.println("no ok");
}
}catch(Exception e){
e.printStackTrace();
}
finally
{
try {
ps.close();
ct.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}