package com.yuan.test; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class Test123 { public Test123() { } public static void main(String[]args){ User user=new User("123", "yuanw", "Man", "yuanw"); Test123 test123=new Test123(); try { test123.updateUser(user); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void updateUser(User user) throws java.sql.SQLException { java.lang.StringBuffer sqlBuf = new java.lang.StringBuffer(); sqlBuf.append("update T_USER set USER_NAME=‘"); sqlBuf.append(user.getUsername()); sqlBuf.append("‘,"); sqlBuf.append("SEX=‘"); sqlBuf.append(user.getSex()); sqlBuf.append("‘,"); sqlBuf.append("email=‘"); sqlBuf.append(user.getEmail()); sqlBuf.append("‘ where userid="); sqlBuf.append(user.getId()); String sql = sqlBuf.toString(); System.out.println("打印update更新语句:"+sql); java.sql.Connection con = getConnectionFromDataSource(); java.sql.Statement stmt = con.createStatement(); stmt.executeUpdate(sql); stmt.close(); con.close(); } private Connection getConnectionFromDataSource() { String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; // 加载JDBC驱动 String dbURL = "jdbc:sqlserver://localhost:1433; DatabaseName=hibernate"; // 连接服务器和数据库test String userName = "sa"; // 默认用户名 String userPwd = "sa123"; // 密码 Connection dbConn = null; try { Class.forName(driverName); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { dbConn = DriverManager.getConnection(dbURL, userName, userPwd); System.out.println("Connection Successful!"); // 如果连接成功 控制台输出Connection } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Successful! return dbConn; } }
注意:需要引入SQLJDBC4.jar 包
小技巧:修改表字段属性值。
alter table tablename alter column colname newDataType
@@兄弟们都帮我看看,这样写 调用会有什么问题呢???
时间: 2024-11-08 04:10:50