简体   繁体   English

如何将JAVA连接到SQL Server 2012?

[英]How to connect JAVA to SQL Server 2012?

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. 嗨,朋友们,我在JAVA中是一个全新的人,我现在想知道如何将JDBC与SQL Server 2012连接。我经历了很多内容,但我没有理解。 So can you give me a sample demo code... 所以可以给我一个示例演示代码...

I have one more problem that i installed SQL Server 2012 but i don't know what is username, password and server name. 我还有一个问题,我安装了SQL Server 2012,但我不知道用户名,密码和服务器名是什么。 SO what can i do for it?? 那我该怎么办呢?

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$1.run(Unknown Source)
    at java.net.URLClassLoader$1.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)

It seems your sql driver classes is not in classpath. 看来您的sql驱动程序类不在classpath中。 if your are using an IDE add it to classpath else add it manually before compiling your class. 如果您使用的是IDE,则将其添加到classpath,否则在编译类之前手动添加它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM