如何将 JAVA 连接到 SQL Server 2012?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22242783/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to connect JAVA to SQL Server 2012?
提问by Shaktisinh Jadeja
Hey friends I am totally new in JAVA and i want to now how to connect JDBC with SQL Server 2012. I go through so much material but i didn't get it. So can you give me a sample demo code...
嘿朋友们,我是 JAVA 的新手,我现在想知道如何将 JDBC 与 SQL Server 2012 连接起来。我浏览了很多材料,但我没有明白。所以你能给我一个示例演示代码...
I have one more problem that i installed SQL Server 2012 but i don't know what is username, password and server name. SO what can i do for it??
我还有一个问题,我安装了 SQL Server 2012,但我不知道用户名、密码和服务器名称是什么。所以我能为它做什么??
When i code it gives error...
当我编码时,它给出了错误...
Code:
代码:
import java.sql.*;
public class Conection
{
public static void main(String a[]) throws ClassNotFoundException, SQLException
{
try
{
String url = "jdbc:sqlserver://localhost:1433//SQLEXPRESS;databaseName=mydb";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(url);
System.out.println("connection created");
Statement st=conn.createStatement();
String sql="select * from mydb";
ResultSet rs=st.executeQuery(sql);
while(rs.next())
{
System.out.println("Name: "+rs.getString(1));
//System.out.println("Address : "+rs.getString(2));
}
if(st!=null)
st.close();
if(conn!=null)
conn.close();
}
catch(SQLException sqle)
{
System.out.println("Sql exception "+sqle);
}
}
}
Error
错误
Exception in thread "main" java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver
at java.net.URLClassLoader.run(Unknown Source)
at java.net.URLClassLoader.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at Conection.main(Conection.java:11)
采纳答案by Shriram
It seems your sql driver classes is not in classpath. if your are using an IDE add it to classpath else add it manually before compiling your class.
看来您的 sql 驱动程序类不在类路径中。如果您使用的是 IDE,请将其添加到类路径中,否则请在编译类之前手动添加它。