package com.spring.test;
import java.sql.*;
class sqlServer {
public static void main(String[] args) throws SQLException {
Sql sql = new Sql();
sql.Select();
// sql.Insert("12s531","黄洪飞8302rw2");
System.out.println();
// sql.Delete("12sdf531");
sql.UpDate("12sdf531", "2");
sql.Select();
sql.Close();
}
}
class Sql {
Connection conn;
Statement stmt;
ResultSet rs;
String url = "jdbc:sqlserver://localhost:1433;DatabaseName=XSCJ;";
public Sql() throws SQLException {
try {
conn = DriverManager.getConnection(url, "sa", "sa");
// 建立Statement对象
stmt = conn.createStatement();
} catch (SQLException e) {
e.printStackTrace();
System.out.println("数据库连接失败");
}
}
public void Select() throws SQLException {
String sql = "select * from student";
// 连接数据库
rs = stmt.executeQuery(sql);
while (rs.next()) {
String Sno = rs.getString("Sno");
String SName = rs.getString("Sname");
System.out.println("Sno:" + Sno + " SName" + SName);
}
}
public void Insert(String Sno, String Sname) throws SQLException {
// PreparedStatement preparedStatement=conn.prepareStatement(sql);
String sql = "insert into Student(Sno,Sname)values(?,?)";
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, Sno);
preparedStatement.setString(2, Sname);
preparedStatement.addBatch();
preparedStatement.executeUpdate();
// preparedStatement.close();
}
public void Delete(String Sno) throws SQLException {
String sql = "delete from Student where Sno=?";
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, Sno);
preparedStatement.executeUpdate();
}
public void UpDate(String Sno, String SName) throws SQLException {
String sql = "update Student set Sname=? where Sno=?";
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, SName);
preparedStatement.setString(2, Sno);
preparedStatement.executeUpdate();
}
public void Close() throws SQLException {
stmt.close();
conn.close();
}
}
java链接到sql2008以及增删改查基本操作代码
最新推荐文章于 2020-08-27 15:53:50 发布