Java链接数据库的基本步骤
1.java 连接数据库
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class MyLink {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver")
.newInstance();
String url = "jdbc:odbc:Driver={SQL Server};Server=localhost;Database=Component";
// mydb为数据库
String user = "sa";
String password = "sa";
Connection conn = DriverManager.getConnection(url, user, password);
PreparedStatement partnames=conn.prepareStatement("SELECT * FROM Part_Name ");
ResultSet rs=partnames.executeQuery();
while(rs.next())
{
String Data=rs.getString("ACL_Part_Name");//读取一列数据,ACL_Part_Name是列名
System.out.println();
}
} catch ( Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
2.另外还有桥接,就是需要在配置系统的数据源之类的,另外还需要改驱动,将ForName中的驱动改下:
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver"); //注册驱动
con = DriverManager.getConnection("jdbc:microsoft:sqlserver:
//你的IP:1433;databaseName=数据库名","sa","你的密码");//