1

I am trying to connect to a SQL Server database in Java, execute a query, and return the result to the calling script.

class DB { public DB() {}

        public Connection dbConnect(String db_connect_string)
        {
                try
                {
                        Class.forName(
                          "com.microsoft.jdbc.sqlserver.SQLServerDriver");

                        Connection conn =
                          DriverManager.getConnection(db_connect_string);

                        System.out.println("connected");
                        return conn;

                }
                catch (Exception e)
                {
                        e.printStackTrace();
                        return true;
                }
        }
};
class getConnection
{
        public void main(String[] args)
        {
                DB db = new DB();
                Connection conn=db.dbConnect(
          "jdbc:microsoft:sqlserver://host:1433;User=user;Password=Pwd");
        }

}
return true;

As far as I can tell this tells me the connection is fine, but my Java is less than limited. Can someone tell me if this part is fine and add a simple select statement to it, which is then passed back via return?

1
  • I recommend to use either JPA or (pooled) DataSources and JdbcTemplate from Spring (should be useable even if you don't use Spring otherwise). Commented Feb 23, 2011 at 10:51

2 Answers 2

2

Perhaps you need to do some reading up.

http://download.oracle.com/javase/tutorial/jdbc/basics/processingsqlstatements.html

Sign up to request clarification or add additional context in comments.

4 Comments

StackOverflow is brilliant, but its no substitute for reading books (or doing a google search) ;-)
I can sense that these days StackOverflow is rather being overwhelmed by questions which can simply be answered by a single RTFM!
StackOverflow used to be quite newbie-friendly. If my question is so easy to answer why doesn't one of you?
@Marius - That is the best answer one can give! We can only show you the way, but not walk you.
2

May be you should brush up how to use JDBC

public Statement getStatement()
{

      return conObject.createStatement();

} 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.