java连接sqlserver2005的代码,还有增删改查的代码是什么

2025-01-03 22:47:50
推荐回答(4个)
回答1:

public final static String DRIVER_CLASS = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
public final static String JDBC_URL = "jdbc:sqlserver://localhost:1433;databaseName=XXXXX";
public final static String USER_NAME = "XXXX";
public final static String USER_PWD = "XXXXXXX";

protected Connection conn;
protected PreparedStatement pstmt;
protected ResultSet rs;
protected Connection getConn() {
Connection conn = null;
try {
Class.forName(DRIVER_CLASS);
conn = DriverManager.getConnection(JDBC_URL, USER_NAME, USER_PWD);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}

protected void closeAll(ResultSet rs, PreparedStatement pstmt, Connection conn) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

查:select * from XXX
增:insert into XXX value(X,X,X,X)
删:delete from XXX
改:update XXX set XXX=?,XXX=? where XXX=?

public int addNews(NewsInfo news) {
int result = 0;

try {
conn = getConn();
pstmt = conn.prepareStatement(“增加的SQL语句”);
pstmt.setString(1, news.getNews_title());
pstmt.setString(2, news.getNews_Info());
pstmt.setString(3, news.getNews_creator());
result = pstmt.executeUpdate();

} catch (SQLException e) {
System.out.println("ÐŽÈëÊýŸÝʧ°Ü£¬ÇëŒì²é²œÖ裡");
e.printStackTrace();
} finally {

closeAll(rs, pstmt, conn);
}
return result;
}

就给你这么多提示吧。

回答2:

增删改查和其他的一样直接用SQL语句
java连接代码
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver") ;
String url="jdbc:microsoftqlserver://localhost:1433;DatabaseName=mydb";
Connection conn = DriverManager.getConnection(url,user,password);
Statement stmtNew = conn.createStatement();
return stmtNew;
}
catch(Exception e)
{
e.printStackTrace();
return null;
}

回答3:

如果是第一次用的话,楼下weining370 可以参考一下。。。。

回答4:

建议你用hibernate,方便多 了,不要用jdbc