Timeout not working in SQL Connection - vb.net

I have this simple code to test that a DB is ready:
Function testlocalcon() As Boolean
Dim constr As String = _clconstr
Try
Using t As New SqlConnection()
constr = constr & " ; Connect Timeout=1"
If Not t.State = Data.ConnectionState.Open Then
t.ConnectionString = constr
t.Open()
If t.State = Data.ConnectionState.Open Then
Return True
Else
Return False
End If
Else
Return True
End If
End Using
Catch ex As Exception
Return False
End Try
End Function
I do not want to execute a query, just to check the connection, but no matter what the time out parameter is ignored. I search here (Stackoverflow) and internet and found nothing in how to fix this.
Any one else have this problem? Or, are there any other ideas on how to let the application know that the DB is ready?

I appologize for the code differenc but this is C# and I have used it in the past. Its pretty simple and should be readable.
private SQLServerConnection
private SqlConnection _SQLServerConnection;
public SqlConnection SQLServerConnection
{
get
{
return _SQLServerConnection;
}
set
{
_SQLServerConnection = value;
}
}
private void SetSQLServerConnectionString (string sqlServerName, string databaseName, string saPassword, int connectTimeout)
{
SQLServerConnection = new SqlConnection("Password=" + saPassword + ";Persist Security Info=True;User ID=sa;Initial Catalog=" + databaseName + ";Data Source=" + sqlServerName + ";connection timeout=" + connectTimeout.ToString(CultureInfo.InvariantCulture));
}
internal bool TestSQLServerConnection(string sqlServerName, string databaseName, string saPassword, int connectTimeout)
{
try
{
SetSQLServerConnectionString(sqlServerName, databaseName, saPassword, connectTimeout);
SQLServerConnection.Open();
return true;
}
catch (SqlException e)
{
return false;
}
finally
{
SQLServerConnection.Close();
}
}

Related

Error while getting records from stored procedure

I have code to take data from stored procedure.
I just want record from stored procedure. But now I am getting error with this code in class with DataAccess code:
SelectCommand.Connection property has not been initialized. fill data adapter
I just want to track all rows with pagination:
namespace SpidiWeb.App_Code.Helper
{
public class DataAccess
{
public string mstr_ConnectionString;
public SqlConnection mobj_SqlConnection;
public SqlCommand mobj_SqlCommand;
public int mint_CommandTimeout = 30;
public void GetConnection(string cnn_type, string dbname)
{
try
{
if (cnn_type == "W")
{
string Cnn_Str = "";
//string ServerName = "SHREE-PC";
//string DBUserName = string.Empty;
//string DBPassword = string.Empty;
string ServerName = ConfigurationManager.AppSettings["SERVER"];
string DBUserName = ConfigurationManager.AppSettings["UID"] ?? string.Empty;
string DBPassword = ConfigurationManager.AppSettings["PASSWORD"] ?? string.Empty;
string Database = dbname;
DBPassword += "c#" + Convert.ToChar(49);
//Cnn_Str = "Server=" + ServerName + ";User Id=" + DBUserName + ";Password=" + DBPassword + ";Initial Catalog=" + Database;
Cnn_Str = "Server=" + ServerName + ";Initial Catalog=" + Database +";Integrated Security=True";
mstr_ConnectionString = Cnn_Str;
}
else if (cnn_type == "S")
{
string Cnn_Str = "";
//string ServerName = "SHREE-PC";
//string DBUserName = string.Empty;
//string DBPassword = string.Empty;
string ServerName = ConfigurationManager.AppSettings["SERVER"];
string DBUserName = ConfigurationManager.AppSettings["UID"] ?? string.Empty;
string DBPassword = ConfigurationManager.AppSettings["PASSWORD"] ?? string.Empty;
string Database = "NEWSMSLOG_" + dbname;
DBPassword += "c#" + Convert.ToChar(49);
//Cnn_Str = "Server=" + ServerName + ";User Id=" + DBUserName + ";Password=" + DBPassword + ";Initial Catalog=" + Database;
Cnn_Str = "Server=" + ServerName + ";Initial Catalog=" + Database + ";Integrated Security=True";
mstr_ConnectionString = Cnn_Str;
}
mobj_SqlConnection = new SqlConnection(mstr_ConnectionString);
mobj_SqlCommand = new SqlCommand();
mobj_SqlCommand.CommandTimeout = mint_CommandTimeout;
mobj_SqlCommand.CommandType = CommandType.StoredProcedure;
mobj_SqlCommand.Connection = mobj_SqlConnection;
mobj_SqlConnection.Open();
}
catch (Exception ex)
{
throw new Exception("Error initializing data class." + Environment.NewLine + ex.Message);
}
and this code is from my page :
DataAccess obj_con = new DataAccess();
protected void Get_Data()
{
try
{
DataTable dt = new DataTable();
int intUserId = ddl_users.SelectedItem.Text.ToString() == "All" ? 0 : Convert.ToInt32(ddl_users.SelectedValue.ToString());
string strCampaignName = string.IsNullOrEmpty(txt_CompaignName.Text.Trim()) ? string.Empty : txt_CompaignName.Text.Trim();
string mobileNo = string.IsNullOrEmpty(txt_mobileno.Text.Trim()) ? string.Empty : txt_mobileno.Text.Trim();
int intSenderId = ddl_sender.SelectedItem.Text.ToString() == "All" ? 0 : Convert.ToInt32(ddl_sender.SelectedValue.ToString());
string strDeliveryId = ddl_delevery.SelectedItem.Text.ToString() == "All" ? "-1" : ddl_delevery.SelectedItem.Text.ToString();
using (var con = obj_con.mobj_SqlConnection)
{
//if (con.State == ConnectionState.Closed)
// con.Open();
var cmd = new SqlCommand();
cmd.Parameters.AddWithValue("intUserID", intUserId);
cmd.Parameters.AddWithValue("strCampaignName", strCampaignName);
cmd.Parameters.AddWithValue("strMobileNo", mobileNo);
cmd.Parameters.AddWithValue("intSenderId", intSenderId);
cmd.Parameters.AddWithValue("strDeliveryId", strDeliveryId);
if (ddl_account.SelectedItem.Text.ToString() == "All")
{
cmd.Parameters.AddWithValue("intAccType", DBNull.Value);
}
else
{
cmd.Parameters.AddWithValue("intAccType", Convert.ToInt32(ddl_account.SelectedValue.ToString()));
}
if (chk_date.Checked == true)
{
DateTime dateValue = Convert.ToDateTime(CommonLogic.Get_Date_From_String(txt_date_from.Text.Trim(), 1));
cmd.Parameters.AddWithValue("strdbNM ", dateValue.ToString("yyyy_MM"));
}
else
{
cmd.Parameters.AddWithValue("strdbNM ", DateTime.Now.Date.ToString("yyyy_MM"));
}
if (!string.IsNullOrEmpty(txt_date_from.Text.Trim()))
{
DateTime date = Convert.ToDateTime(txt_date_from.Text.Trim());
cmd.Parameters.AddWithValue("strTBNM", date.ToString("ddMMyy"));
}
else
{
cmd.Parameters.AddWithValue("strTBNM", DateTime.Now.Date.ToString("ddMMyy"));
}
cmd.Parameters.AddWithValue("PageIndex", 1);
cmd.Parameters.AddWithValue("PageSize", 1000);
cmd.Parameters.Add("RecordCount", SqlDbType.Int).Direction = ParameterDirection.Output;
cmd.Connection = con;
cmd.CommandText = "dbo.Report_ViewCombineReport";
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter ad = new SqlDataAdapter(cmd);
ad.SelectCommand = cmd;
ad.Fill(dt); // Error Occurs here Fill: SelectCommand.Connection property has not been initialized.
egrd.DataSource = dt;
egrd.DataBind();
}
}
catch (Exception ex)
{
CommonLogic.SendMailOnError(ex);
}
}
You didn't pass Connection to SqlCommand object, pass it in parameter like below
var cmd = new SqlCommand("Your query", con);
Or you can also set it by
cmd.Connection = con;

OR statement in SQL command does not function

Does anyone know to fix the error? I would like to create the OR statement but it does not function in my code. The code is shown below. I have removed the OR to see the code function or not, it can function if I remove the or statement. So I desperately want to know what the real problem with my code is.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
public partial class updateform : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=.\\sqlexpress;Initial Catalog=test;Integrated Security=True");
SqlDataAdapter sda = new SqlDataAdapter("Select * FROM [EMP] WHERE Serial_Num='" + TextBox2.Text + "' or Equipment_ID ='" + TextBox1.Text + "'", con);
DataTable dt = new DataTable();
sda.Fill(dt);
TextBox3.Text = dt.Rows[0][2].ToString();
TextBox4.Text = dt.Rows[0][6].ToString();
DropDownList1.Text = dt.Rows[0][7].ToString();
TextBox5.Text = dt.Rows[0][18].ToString();
TextBox6.Text = dt.Rows[0][11].ToString();
TextBox11.Text = dt.Rows[0][8].ToString();
TextBox7.Text = dt.Rows[0][20].ToString();
TextBox12.Text = dt.Rows[0][17].ToString();
DropDownList2.Text = dt.Rows[0][23].ToString();
TextBox9.Text = dt.Rows[0][14].ToString();
TextBox10.Text = dt.Rows[0][13].ToString();
TextBox13.Text = dt.Rows[0][12].ToString();
TextBox2.Text = dt.Rows[0][5].ToString();
TextBox1.Text = dt.Rows[0][4].ToString();
}
protected void Button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source =.\\sqlexpress; Initial Catalog = test; Integrated Security = True");
con.Open();
SqlCommand cmd = new SqlCommand(#"UPDATE EMP SET Model='" + TextBox3.Text + "' ,Description= '" + TextBox4.Text + "' ,Location='" + DropDownList1.Text + "',Manufacturer_or_Vendor= '" + TextBox5.Text + "',NCR_or_OOT_History='" + TextBox6.Text + "',Due_date= '" + TextBox11.Text + "' ,Year_of_Manufacturing='" + TextBox12.Text + "',Asset_No= '" + TextBox7.Text + "' ,Status='" + DropDownList2.Text + "',Responsible_Person= '" + TextBox9.Text + "',Available_in_Sapphire= '" + TextBox10.Text + "',Last_OOT_issuance_Date= '" + TextBox13.Text + "' WHERE (Serial_Num = '" + TextBox2.Text + "' or Equipment_ID = '" + TextBox1.Text + "' )", con);
cmd.ExecuteNonQuery();
con.Close();
}
protected void Page_load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Calendar1.Visible = false;
Calendar2.Visible = false;
Calendar3.Visible = false;
}
}
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
if (Calendar1.Visible)
{
Calendar1.Visible = false;
}
else
{
Calendar1.Visible = true;
}
}
protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
{
if (Calendar2.Visible)
{
Calendar2.Visible = false;
}
else
{
Calendar2.Visible = true;
}
}
protected void ImageButton3_Click(object sender, ImageClickEventArgs e)
{
if (Calendar3.Visible)
{
Calendar3.Visible = false;
}
else
{
Calendar3.Visible = true;
}
}
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
TextBox11.Text = Calendar1.SelectedDate.ToString("dd/MM/yyyy");
Calendar1.Visible = false;
}
protected void Calendar2_SelectionChanged(object sender, EventArgs e)
{
TextBox12.Text = Calendar2.SelectedDate.ToString("dd/MM/yyyy");
Calendar2.Visible = false;
}
protected void Calendar3_SelectionChanged(object sender, EventArgs e)
{
TextBox13.Text = Calendar1.SelectedDate.ToString("dd/MM/yyyy");
Calendar3.Visible = false;
}
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
if (e.Day.IsOtherMonth)
{
e.Day.IsSelectable = false;
}
}
protected void Calendar2_DayRender(object sender, DayRenderEventArgs e)
{
if (e.Day.IsOtherMonth)
{
e.Day.IsSelectable = false;
}
}
protected void Calendar3_DayRender(object sender, DayRenderEventArgs e)
{
if (e.Day.IsOtherMonth)
{
e.Day.IsSelectable = false;
}
}
protected void Button3_Click(object sender, EventArgs e)
{
Response.Redirect("Default.aspx");
}
}
It is not clear from your description whether it fails at compile time or execution time, or what the error is. But a wild guess of what could be the problem, try the followings:
Instead of Select * try specifying the actual columns (like select col1, col2, ..
Instead of:
sda.Fill(dt);
Declare a dataset and fill the dataset and see if it works.
DataSet ds = new DataSet ();
sda.Fill (ds);
If this works, check and see how many tables are created in your dataset and what records are in each table.

async function in mvc4 vb.net

i have the below structure :
this is my controller :
Public Function InsertRegistration() as string
dim res = t.Insertregistration(jsonparam.status)
return res
End Function
this is my class :
Public Function InsertRegistration(byval status as string) as string
sql.Insertregistration(status)
return "1"
End Function
this is my model function :
Public Function InsertRegistration(ByVal status As String) As Boolean
Dim TConnSQL As New SqlConnection(sql)
Dim CommSQL As New SqlClient.SqlCommand("JK_SP_INSERT_PROFILE", TConnSQL)
Dim paramSQL As SqlClient.SqlParameter
Dim data_ada As SqlDataAdapter
Dim dt As DataSet
Try
CommSQL.CommandType = CommandType.StoredProcedure
paramSQL = New SqlClient.SqlParameter("#STATUS", SqlDbType.NVarChar, 100)
paramSQL.Direction = ParameterDirection.Input
paramSQL.Value = STATUS
CommSQL.Parameters.Add(paramSQL)
CommSQL.ExecuteNonQuery()
InsertRegistration= True
Catch ex As System.Data.SqlClient.SqlException
WriteToText("Nbl.InsertRegistration", ex.ToString)
InsertRegistration= False
Catch ex As Exception
WriteToText("Nbl.InsertRegistration", ex.ToString)
InsertRegistration= False
Finally
If (IsNothing(CommSQL) = False) Then CommSQL.Dispose()
If TConnSQL.State <> ConnectionState.Closed Then TConnSQL.Close()
End Try
End Function
is there a way to return the result 1 in an asynchronous way that the function sql.Insertregistration(status) keeps running in background after i return the result to the client?
Simply put your function sql.Insertregistration(status) as in below code:
(new Task<bool>(() =>
{
return sql.Insertregistration(status);
})).Start();
Note: Please take care of the cross thread ooperations.

Selenium2 - Running tests on CI causes multiple driver instances

For our BDD tests we use Specflow that talks to selenium 2 webdriver (Chrome driver in this instance).
While running on local host (Yes, "it works on my machine" has came up in conversation a few times) the tests work fine. They setup the data and a new webdriver, do the test and then tear down the webdriver and data. Even if a test goes horribly wrong because I'm using correct attributes the tear down is always hit and therefore driver.Quit() is run destroying the browser and the driver.
The problem arises when I run it on our server [Windows Server 2008 r2] using our continuous integration [TeamCity]. For some reason it will start to run multiple driver instances which cause the tests to fail.
Has anyone ran into this problem before and found a fix? We need a solution that uses a driver that isn't HtmlUnitDriver.
Extra information:
Language = C#
Server = Windows Server 2008 R2
CI = TeamCity
EDIT:
The Webdriver is set up by making sure that it isn't already created and then creates a new instance of the ChromeDriver. Pseudo/real code example bellow shows how its set up, sorry I cant show the full code as it has to much fluff in that we use for other options that we stick in (e.g zap or fiddler integration / language changes etc).
Setup
[SetUp]
[BeforeScenario()]
public static void BeforeWebScenario()
{
if driver == null
driver = new ChromeDriver();
// Code to start page
}
Tear down
[TearDown]
[AfterScenario()]
public static void AfterWebScenario()
{
try
{
driver.Quit();
} catch (Exception)
{
throw Exception
}
driver = null;
}
I had this problem too. I fixed it by killing any running instances of chromedriver.exe in my testSetup() method. I used a VBScript and some Groovy code to run the scripts. Sorry this answer is kind of long.
I had this in my setUp):
if (wshsc.isRunningByCommandLineContents("chromedriver.exe"))
wshsc.killProcessByCommandLineContents("chromedriver.exe")
isRunningByCommandLineContents:
If WScript.Arguments.Count = 1 Then
strCmdLine = WScript.Arguments.Item(0)
On Error Resume Next
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set objShell = CreateObject("WScript.Shell")
Set colProcessList = objWMIService.ExecQuery _
("Select * from Win32_Process")
If colProcessList.Count > 0 Then
For Each objItem in colProcessList
If (InStr(objItem.CommandLine, strCmdLine)) Then
If (InStr(objItem.CommandLine, "cscript")) Then
Else
WScript.StdOut.Write "A process is running with " + strCmdLine + " in its command line = " + objItem.Name
End If
End If
Next
End If
End If
killProcessByCommandLineContents:
If WScript.Arguments.Count = 1 Then
strProcess = WScript.Arguments.Item(0)
On Error Resume Next
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set objShell = CreateObject("WScript.Shell")
Set colProcessList = objWMIService.ExecQuery _
("Select * from Win32_Process")
If colProcessList.Count > 0 Then
For Each objItem in colProcessList
If InStr(objItem.CommandLine, strProcess) Then
If (InStr(objItem.CommandLine, "cscript")) Then
Else
WScript.StdOut.Write objItem.Name + " "
objItem.Terminate()
End If
End If
Next
Else
WScript.StdOut.Write "No instances found running"
End If
Else
WScript.StdOut.Write "Bad Arguments"
End If
And the "run the scripts part":
public void killProcessByCommandLineContents(String contents) {
List<String> arg = new ArrayList<String>()
arg.add(contents)
String [] args = arg.toArray()
runScript("killByCmdLineContents.vbs", args, true)
}
public boolean isRunningByCommandLineContents(String contents) {
List<String> arg = new ArrayList<String>()
arg.add(contents)
String [] args = arg.toArray()
String returnData = runScript("IsRunningByCmdLineContents.vbs", args, true)
if (returnData.contains(contents)) {
return true
} else {
return false
}
}
public String runScript(String name, String [] args, boolean returnOutput) {
String s = null;
List<String> cmdLine = new ArrayList<String>()
cmdLine.add("C://Windows//System32//cscript.exe")
cmdLine.add(dir + "dir//src//com//misc//wshScripts//" + name)
int index = 0
args.each() {
cmdLine.add(args[index])
index++
}
try {
String [] cmdLineArray = cmdLine.toArray()
Process p = Runtime.getRuntime().exec(cmdLineArray, null);
if (returnOutput) {
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String dataToReturn
Log.logger.info("Standard output: ");
while ((s = stdInput.readLine()) != null) {
Log.logger.info(s)
dataToReturn = s // should get last line
}
Log.logger.info("Standard error: ");
while ((s = stdError.readLine()) != null) {Log.logger.info(s);}
return dataToReturn
} else {
return ""
}
}
catch (IOException e) {
Log.logger.info(e.message, e);
}
}
If you use the DriverService interface, hold onto the service until you're done with the driver, and call DriverService.stop() as well. For me, the driver.quit() wasn't enough because I was using DriverService as well.
driver.close();
driver.quit();
driverService.stop();

lotuscript: some questions about connecting to a SQL DB

I've got this code that is working... I read from an MS SQL database some rows from a table and then send an email for each row.
I'm about to add an "attachment" field, on my SQL database and I'd like to add the attachment at the end of my body.
I have two questions: 1) what datatype should I use on MS SQL? (Binary field, maybe) and 2) if someone else has some example code, I'd really appreciate it.
A bonus question: on a more advanced version of this script, i first run by all my results from my resultset to get the IDs from the messages and then update their status on the MS SQL table.
Then I try and run by the same resultset again, to actually perform the sending....
Somehow, on the second run, I'm having trouble starting from row 1, using the same code than bellow... any advice on what's the best way to do that?: My requirement is that I have to run twice by the same resultset. :)
Thanks in advance.
Option Public
Uselsx "*LSXODBC"
Sub Initialize
Dim session As New NotesSession
Dim db As NotesDatabase
Dim doc As NotesDocument
Dim subject As String, cc As String, bcc As String, sender As String, OID As String, mailto As String, bodyNotMIME As String
Dim body As NotesMIMEEntity
On Error Goto errorCounter
Set db = session.CurrentDatabase
Gosub SendMailGeneral
Exit Sub
SendMailGeneral:
Dim con As New ODBCConnection
Dim qry As New ODBCQuery
Dim result As New ODBCResultSet
Dim defaultQuery As String
Set qry.Connection = con
con.SilentMode = True
If con.ConnectTo("DSN_Name","USER_NAME", "PASSWORD") Then
Set result.Query = qry
defaultQuery = "select TOP (10) * from Message where StatusType=0"
qry.SQL = defaultQuery
result.Execute
If (result.IsResultSetAvailable) Then
Do
result.NextRow
Gosub GetRowFields
Gosub SendMail
Loop Until result.IsEndOfData
End If
End If
result.Close(DB_CLOSE)
Return
End Sub
GetRowFields:
mailto = result.GetValue("To")
cc = result.GetValue("CC")
bcc = result.GetValue("Bcc")
sender = result.GetValue("Sender")
subject = result.GetValue("Subject")
bodyNotMIME = result.GetValue("Body")
OID = result.GetValue("OID")
Return
SendMail:
Dim mail As NotesDocument
Set mail = New NotesDocument(db)
Dim stream As NotesStream
Set stream = session.CreateStream
'Recipients
mail.SendTo = mailto
mail.CopyTo = cc
mail.BlindCopyTo = bcc
' Set all sender-related fields
mail.ReplyTo = sender
mail.Principal = sender
mail.From = sender
mail.AltFrom = sender
mail.SendFrom = sender
mail.INetFrom = sender
mail.tmpDisplaySentBy = sender
mail.tmpDisplayFrom_Preview = sender
mail.DisplaySent = sender
'Body
Call stream.WriteText(bodyNotMIME)
Set body = mail.CreateMIMEEntity
Call body.SetContentFromText _
(stream, "text/html; charser=iso-8859-1", ENC_NONE)
'Subject
mail.Subject = subject
'Send
Call mail.Send(False, False)
Return
Wasn't this line:
result.NextRowcode
supposed to be:
result.NextRow
?
I don't know about MSSQL, but in DB2 we routinely use Blob/Clob binary data type to store any type of files.
I hear that many MSSQL experts recommend rather storing files on file system with only their path and file name in a DB.
OK, here's the abbreviated code from my Java ScriptLibrary that uses JDBC to connect to DB2 and execute a query (you would only need to import your db's jar-s and use com.microsoft.sqlserver.jdbc.SQLServerDriver for MS SQL):
import java.sql.*;
import com.ibm.db2.jcc.DB2Driver;
public class DB2Connection {
protected String server;
protected String port;
protected String dbName;
protected String userdb2;
protected String pwddb2;
protected java.sql.Connection con;
public DB2Connection( String srv, String port, String db, String user, String pass ){
this.server = srv;
this.port = port;
this.dbName = db;
this.userdb2 = user;
this.pwddb2 = pass;
connectDB2();
}
public void connectDB2() {
try {
Class.forName("com.ibm.db2.jcc.DB2Driver"); // .newInstance();
String url = "jdbc:db2://" + server + ":" + port + "/" + dbName;
con = DriverManager.getConnection(url, userdb2, pwddb2);
System.out.println("Connection to DB2 succeded");
} catch (Exception e) {
System.out.println("Error connecting DB2 Server") ;
e.printStackTrace();
}
}
protected ResultSet executeQuery( String queryString ) throws SQLException, Exception {
System.out.println( "Preparing query:\t" + queryString );
ResultSet rs = null;
try {
Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
rs = stmt.executeQuery(queryString);
} catch (SQLException sqle) {
String error = ("SQLException : Could not execute query");
throw new SQLException(error);
} catch (Exception e) {
String error1 = ("Exception : An Unknown error occurred.");
throw new Exception(error1);
}
return rs;
}
protected int executeCountQuery( StringBuffer queryStr ){
System.out.println( "Preparing query:\t" + queryStr );
try {
ResultSet rs = executeQuery( queryStr.toString( ) );
rs.next(); //only one row in result set
return rs.getInt(1);
} catch (SQLException sqle) {
System.out.println("SQLException: Could not get ResultSet from DB2Connection.executeQuery");
sqle.printStackTrace();
} catch (Exception e) {
System.out.println("Exception : An Unknown error occurred while calling.");
e.printStackTrace();
}
return 0;
}
protected int executeCountQuery( PreparedStatement ps ){
//System.out.println( "Preparing prepared statement - query:\t" ); //+ ps.getQuery( ) );
try {
ResultSet rs = ps.executeQuery( );
rs.next(); //only one row in result set
return rs.getInt(1);
} catch (SQLException sqle) {
System.out.println("SQLException: Could not get ResultSet from DB2Connection.executeQuery");
sqle.printStackTrace();
} catch (Exception e) {
System.out.println("Exception : An Unknown error occurred while calling.");
e.printStackTrace();
}
return 0;
}
public Connection getConnection(){
return con;
}
}
To check out the examples of using LS2J to use Java classes directly from your LotusScript code, download this great LS2J samples database from Julian Robichaux:
http://www.nsftools.com/tips/NotesTips.htm#ls2jexamples
And here's a good link to start with, explains how to use JDBC with MS SQL server:
http://support.microsoft.com/kb/313100