Java 中连接数据库的jdbc 怎么用的谁能给个例子 秒加分了
2个回答
推荐于2016-05-14
展开全部
package demo;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class ConnectSQL2005
{
// 不区分大小写
private static final String USER = "sA";
private static final String PASSWORD = "1234";
// 不区分大小写
// 20091018-1822
// LoCALHOST
// 127.0.0.1
private static final String HOST = "127.0.0.1";
private static final String PORT = "1433";
public static Connection getConnection ( String databaseName )
{
Connection connection = null;
// jdbc:sqlserver 区分大小写
String url = "jdbc:sqlserver://" + HOST + ":" + PORT;
if (null != databaseName && !"".equals (databaseName))
{
// 不区分大小写
url += ";databaseName=" + databaseName;
}
try
{
Class.forName ("com.microsoft.sqlserver.jdbc.SQLServerDriver");
connection = DriverManager.getConnection (url, USER, PASSWORD);
return connection;
}
catch (ClassNotFoundException e)
{
e.printStackTrace ();
}
catch (SQLException e)
{
e.printStackTrace ();
}
return null;
}
public static void selectInfo ( String db, String sql )
{
Connection connection = ConnectSQL2005.getConnection (db);
if (null == connection)
{
return;
}
Statement stmt = null;
ResultSet rs = null;
try
{
stmt = connection.createStatement ();
rs = stmt.executeQuery (sql);
while (rs.next ())
{
System.out.print (rs.getString (1) + " ");
System.out.print (rs.getString (2));
System.out.println ();
}
}
catch (SQLException e)
{
e.printStackTrace ();
}
finally
{
close (rs, null, stmt, connection);
}
}
public static int executeInfo ( String db, String sql )
{
Connection connection = ConnectSQL2005.getConnection (db);
PreparedStatement ps = null;
int count = -1;
try
{
ps = connection.prepareStatement (sql);
count = ps.executeUpdate ();
}
catch (SQLException e)
{
e.printStackTrace ();
}
finally
{
close (null, ps, null, connection);
}
return count;
}
private static void close ( ResultSet rs, PreparedStatement ps, Statement stmt, Connection connection )
{
try
{
if (null != rs)
{
rs.close ();
}
if (null != ps)
{
ps.close ();
}
if (null != stmt)
{
stmt.close ();
}
if (null != connection)
{
connection.close ();
}
}
catch (SQLException e)
{}
}
public static void main ( String[] args )
{
String deleteSql = "delete from dbo.test where id = 3";
ConnectSQL2005.executeInfo ("master", deleteSql);
String sql = "select * from dbo.test";
ConnectSQL2005.selectInfo ("master", sql);
String insertSql = "insert into dbo.test values (3, '大雄&哆啦A梦')";
ConnectSQL2005.executeInfo ("master", insertSql);
ConnectSQL2005.selectInfo ("master", sql);
}
}
追问
把数据库里的 desc 出来的东东 我看看
追答
select id from table where name='a' order by id desc;
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询