安装SQL 2014
基本知识
删除mysql服务:CMD - sc delete mysql
window验证:只有本机能访问该数据库;混合验证:可在其他pc端通过账号密码来访问该数据库。
字段:列
DDL 数据定义语句
DML 数据操作语句
DCL 数据库控制语句
char(10) 可存放10个汉字,如果汉字不够10个,会补空格。
varchar(10) 可以存放10个汉字,如果汉字不够10个,不补空格。
查表
use JDBCTest
select * from Students
插入数据
use JDBCTest
insert into Students(name, sex, age)
values('李华平','男','28')
JDBC
java中使用数据库需要用JDBC来连接和操作
下载sqljdbc4.jar
把sqljdbc4.jar放入java的安装包中:...\jdk1.7.0_05\jre\lib\ext
在 “开始” 中打开SQL配置管理器 - 网络配置 - MSSQLSERVER协议 - 启用“TCP/IP” - 双击“TCP/IP” - “IP 地址”
- “IPAll” - “TCP 端口” - 添加默认的“1433”
CodeDemo
import java.sql.*;
public class MyDML {
private static String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; // JDBC驱动路径
private static String dbURL = "jdbc:sqlserver://localhost:1433; DatabaseName=JDBCTest"; // dbURL路径
private static String userName = "sa"; // 默认用户名
private static String userPwd = "123456"; // 密码
private static Connection conn = null; // 连接实例
private static Statement st = null; // Statement类用于执行SQL语句
public static void main(String[] srg) throws SQLException {
try {
Class.forName(driverName); // 加载JDBC驱动
conn = DriverManager.getConnection(dbURL, userName, userPwd); // 连接数据库服务器及某数据库
st = conn.createStatement(); // 为该连接创建Statement实例
System.out.println( "Connection Successful! "); // 连接成功
} catch (Exception e) {
e.printStackTrace();
}
//read();
//update();
//delete();
create();
read();
free();
}
static void read() throws SQLException{ // 查询操作
ResultSet resultset = null; // 查询语句会返回一个结果集对象
try {
resultset = st.executeQuery("select name,sex,age from Students");
while(resultset.next()) {
System.out.println(resultset.getObject("name"));
System.out.println(resultset.getObject("sex"));
System.out.println(resultset.getObject("age"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if(resultset!=null)
resultset.close(); // 回收ResultSet对象
}
}
static void create() throws SQLException { // 创建操作
st = conn.createStatement();
String sql = "insert into Students(name,sex,age) values('李华平','男','28')";
st.executeUpdate(sql);
}
static void update() throws SQLException { // 更新操作
st=conn.createStatement();
String sql = "update Students set age = age + 10";
st.executeUpdate(sql);
}
static void delete() throws SQLException { // 删除操作
String sql="delete from Students where age > 20";
st.executeUpdate(sql);
}
public static void free() { // 释放资源
try {
if(st!=null)
st.close(); // 回收Statement对象
} catch (SQLException e) {
e.printStackTrace();
} finally {
if(conn!=null) {
try {
conn.close(); // 回收Connection对象
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}