Java连接SQL数据库
方法一:安装Microsoft SQL Server 2000 Driver for JDBC后,将lib目录下的msbase.jar , mssqlserver.jar, msutil.jar 复制到JDK的主目录下,具体是jdk1.4jrelibext . 完成后编写一下代码
原理:使用jdbc-odbc桥进行连接
try{
Connection con;
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver"); //注册驱动
con = DriverManager.getConnection("jdbc:microsoft:sqlserver://你的IP:1433;databaseName=数据库名","sa","你的密码");//
Statement sta = con.createStatement(); //执行sql语句的容器
String str = "select * from 表名";
ResultSet re = sta.executeQuery(str); //执行完的结果赋给 ResultSet
while(re.next()){ //通过游标对数据进行访问
String 字段名= re.getString("字段名");
System.out.println(字段名);
}
方法二:直接连接。
try{
Connection conn;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn=DriverManager.getConnection("jdbc:odbc:Driver={SQL Server};Server=你的IP;uid=sa;pwd=密码;Database=Northwind");
String sql="select * from Categories";
Statement st=conn.createStatement();
ResultSet rs=st.executeQuery(sql);
while (rs.next())
{
String CategoryName=rs.getString("CategoryName");
System.out.println(CategoryName);
}
}
catch(Exception e){
System.out.println(e.toString());
}
--测试--
import java.sql.*;
public class ZSqlData {
public static void main(String[] args)
{
try{
Connection conn;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn=DriverManager.getConnection("jdbc:odbc:Driver={SQL Server};Server=asatdgibl1;uid=asat;pwd=asat123;Database=asat");
String sql="select top 10 * from tb_sublot";
Statement st=conn.createStatement();
ResultSet rs=st.executeQuery(sql);
while (rs.next())
{
String Sublot_no=rs.getString("Sublot_no");
System.out.println(Sublot_no);
}
}
catch(Exception e){
System.out.println(e.toString());
}
}
}
---Result----
K34964.1$F
PD4Y08F
3667210$1
728137
CM9827.00.1E
PF342517X01
PF342517X01
A4A01010
A4A01012
PD4Z02F
来源:https://www.cnblogs.com/sesexxoo/archive/2008/01/29/6190305.html