Incorrect syntax near ( SQL Update command) - sql

Seems a simple syntax error but need help.
protected void editback_Click(object sender, EventArgs e)
{
String EditStoryID = DropDownList3.SelectedItem.Value;
String EditProjectID = DropDownList1.SelectedItem.Value;
String EditRequirement = TextBoxBacklog.Text;
String EditLock = "0";
String connectionString = WebConfigurationManager.ConnectionStrings["ScrumString"].ConnectionString;
SqlConnection myConnection = new SqlConnection(connectionString);
myConnection.Open();
String query = "UPDATE product_backlog SET (project_id=#project_id,user_story=#user_story,is_locked=#is_locked) WHERE project_backlog.id = (#id)";
SqlCommand commandEdit = new SqlCommand(query, myConnection);
commandEdit.Parameters.AddWithValue("#project_id", EditProjectID);
commandEdit.Parameters.AddWithValue("#id", EditStoryID);
commandEdit.Parameters.AddWithValue("#user_story", EditRequirement);
commandEdit.Parameters.AddWithValue("#is_locked", EditLock);
commandEdit.ExecuteNonQuery();
Page.Response.Redirect(Page.Request.Url.ToString(), true);
Labelsuccess.Text = "User story has been updated";
TextBoxBacklog.Text = "";
}

The set clause should not be surrounded by parentheses:
UPDATE product_backlog
SET project_id = #project_id,
user_story = #user_story,
is_locked = #is_locked
WHERE project_backlog.id = (#id);

You must remove the parentheses after the SET statement.
They are excepted after the WHERE statement but the SET must be without, even if you have more than 1 field you want to update
UPDATE your_table SET key=#value WHERE id = (#id)

Related

How do I export the result of a query to an Excel file?

Given the following query:
String SQL = "select name,years from person";
ps = con.createStatement();
rs = ps.executeQuery(SQL);
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
How can I easily export data to an Excel file?
Thank you
try Apache POI... http://poi.apache.org/
Workbook wb = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Java Books");
// create header row
HSSFRow headerRow = sheet.createRow(0)
Cell nameHeaderCell = headerRow.createCell(0);
Cell addressHeaderCell = headerRow.createCell(1);
String sql = "select name, address from student";
PrepareStatement ps = connection.prepareStatement(sql);
ResultSet resultSet = ps.executeQuery();
int row = 1;
while(resultSet.next()) {
String name = resultSet.getString("name");
String address = resultSet.getString("address");
Row dataRow = sheet.createRow(row);
Cell dataCell = dataRow.createCell(0);
dataCell.setCellValue(name);
Cell dataAddressCell = dataRow.createCell(1);
dataAddressCell.setCellValue(address);
row = row + 1;
}
String outputDirPath = "";//PATH for export location
FileOutputStream fileOut = new FileOutputStream(outputDirPath);
wb.write(fileOut);
fileOut.close();

VB.net Postgres Parameterized Query return no result

I have this function in Visual Basic:
Private Function getpsqlsingle() As String
sqlquery = "select username from web_user where email = '#email' and is_temporary='f'"
Dim email As String = "test#test.com"
Dim psqlconnection As NpgsqlConnection = New NpgsqlConnection("Server=" & signiantserver & ";port=5432;User Id=postgres;Database=DTM_DB")
psqlconnection.Open()
Dim psqlcommand As NpgsqlCommand = New NpgsqlCommand(sqlquery, psqlconnection)
psqlcommand.CommandType = CommandType.Text
Dim param As NpgsqlParameter = New NpgsqlParameter("#email", NpgsqlTypes.NpgsqlDbType.Text)
param.Value = email
psqlcommand.Parameters.Add(param)
Dim value = psqlcommand.ExecuteScalar
psqlconnection.Close()
Return value
End Function
I get no exception thrown yet i still do not get any result back. I do have this test#test.com in my DB and when I run it in pgAdmin4
(select username from web_user where email = 'test#test.com' and is_temporary='f')
I do get a result back. Is there something I am not setting? Any help is appreciated.

Object reference not set to an instance of an object. What's wrong with this code? I am having this error when I run the page [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
string user = string.Empty;
string constr = ConfigurationManager.ConnectionStrings["StatusConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
string result = "SELECT [UserID],[Status] FROM [MSCAssignment].[dbo].[StatusButton] WHERE [Status]='1'";
con.Open();
SqlCommand showresult = new SqlCommand(result, con);
SqlDataReader rd = showresult.ExecuteReader();
//string dd = rd["UserID"].ToString();
CheckBoxList chkbx = (CheckBoxList)FindControl("UserID");
//ListItem currentCheckBox = chkbx.Items.FindByValue(rd["UserID"].ToString());
for (int i = 0; i < chkbx.Items.Count; i++)
{
if (chkbx.Items[i].Selected)
{
user = chkbx.Items[i].Value = ";";
}
}
This line would throw the error if the connection string was not found:
string constr = ConfigurationManager.ConnectionStrings["StatusConnectionString"].ConnectionString;
This will throw the error if the control doesnt' exist:
CheckBoxList chkbx = (CheckBoxList)FindControl("UserID");

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

How do i change logon info dynamically in crystal report and ms access?

I have my crystal reports file accessing data from msaccess database.
now while loading report i need to pass the logon info of the msaccess database along with the database name from vb.net.
I tried using
Dim ConnInfo As ConnectionInfo = New ConnectionInfo()
CRpt.ReportOptions.EnableSaveDataWithReport = False
ConnInfo.IntegratedSecurity = False
ConnInfo.ServerName = ""
ConnInfo.UserID = ""
ConnInfo.Password = ""
ConnInfo.DatabaseName = OLEDBLayer.GetDBLocation()
ConnInfo.Type = ConnectionInfoType.DBFile
'CCINFo.ServerName =
For Each CTable As Table In CRpt.Database.Tables
CTableLogInfo = CTable.LogOnInfo
CTableLogInfo.ConnectionInfo = ConnInfo
'CTable.Location = OLEDBLayer.GetDBLocation
CTable.ApplyLogOnInfo(CTableLogInfo)
Next
But not working. What am i missing?
You can use the following code to apply certain connection details for a report at run time.
Sorry, code in c#.
Please use that method just after loading report rpt file, and before printing/exporting/viewing it.
public static void CrystalReportLogOn(ReportDocument reportParameters,
string serverName,
string databaseName,
string userName,
string password)
{
TableLogOnInfo logOnInfo;
ReportDocument subRd;
Sections sects;
ReportObjects ros;
SubreportObject sro;
if (reportParameters == null)
{
throw new ArgumentNullException("reportParameters");
}
try
{
foreach (CrystalDecisions.CrystalReports.Engine.Table t in reportParameters.Database.Tables)
{
logOnInfo = t.LogOnInfo;
logOnInfo.ReportName = reportParameters.Name;
logOnInfo.ConnectionInfo.ServerName = serverName;
logOnInfo.ConnectionInfo.DatabaseName = databaseName;
logOnInfo.ConnectionInfo.UserID = userName;
logOnInfo.ConnectionInfo.Password = password;
logOnInfo.TableName = t.Name;
t.ApplyLogOnInfo(logOnInfo);
t.Location = t.Name;
}
}
catch
{
throw;
}
sects = reportParameters.ReportDefinition.Sections;
foreach (Section sect in sects)
{
ros = sect.ReportObjects;
foreach (ReportObject ro in ros)
{
if (ro.Kind == ReportObjectKind.SubreportObject)
{
sro = (SubreportObject)ro;
subRd = sro.OpenSubreport(sro.SubreportName);
try
{
foreach (CrystalDecisions.CrystalReports.Engine.Table t in subRd.Database.Tables)
{
logOnInfo = t.LogOnInfo;
logOnInfo.ReportName = reportParameters.Name;
logOnInfo.ConnectionInfo.ServerName = serverName;
logOnInfo.ConnectionInfo.DatabaseName = databaseName;
logOnInfo.ConnectionInfo.UserID = userName;
logOnInfo.ConnectionInfo.Password = password;
logOnInfo.TableName = t.Name;
t.ApplyLogOnInfo(logOnInfo);
}
}
catch
{
throw;
}
}
}
}
}
I searched alot and finally after testing my self by creating new report using static data i got the solution for dynamic one.
My test Procedure:
1.) Created new Crystal Report file:
2.) Created new Database Connection to the .accdb access 2007 file
3.) Created new Form
4.) Added Crystal Report Viewer control on the form
5.) Assigned the report document to the previously created report.
6.) set break point on load of the form
7.) Read all the settings
8.) Copied the settings of the report document, document tables logon info.
9.) Pasted the settings read to my project.
10.) Worked fine... :)
My Code :
//here crpt is a sample report document
Dim CTableLogInfo As TableLogOnInfo
Dim ConnInfo As CrystalDecisions.Shared.ConnectionInfo = New ConnectionInfo()
ConnInfo.Type = ConnectionInfoType.CRQE
ConnInfo.ServerName = DBLayer.GetAbsoluteDBPath()
ConnInfo.DatabaseName = ""
ConnInfo.UserID = "Admin"
ConnInfo.AllowCustomConnection = False
ConnInfo.IntegratedSecurity = False
For Each CTable As Table In CRpt.Database.Tables
CTable.LogOnInfo.ConnectionInfo = ConnInfo
CTableLogInfo = CTable.LogOnInfo
CTableLogInfo.ReportName = CRpt.Name
CTableLogInfo.TableName = CTable.Name
CTable.ApplyLogOnInfo(CTableLogInfo)
Next
CrystalReportViewer1.ReportSource = CRpt
CrystalReportViewer1.RefreshReport()
I got the point that setting the database path to the servername would resolve that
Try this out:
Dim CTableLogInfo As TableLogOnInfo
Dim ConnInfo As CrystalDecisions.Shared.ConnectionInfo = New ConnectionInfo()
Dim CRpt As New ReportDocument
String filename = "rptSales.rpt"
ConnInfo.Type = ConnectionInfoType.CRQE
ConnInfo.ServerName = AppSettings("server")
ConnInfo.DatabaseName = AppSettings("dbNm")
ConnInfo.UserID = AppSettings("username")
ConnInfo.Password = AppSettings("pas")
ConnInfo.AllowCustomConnection = False
ConnInfo.IntegratedSecurity = False
CRpt.Load(AppSettings("reppath") & filename)
For Each CTable As Table In CRpt.Database.Tables
CTable.LogOnInfo.ConnectionInfo = ConnInfo
CTableLogInfo = CTable.LogOnInfo
CTableLogInfo.ReportName = CRpt.Name
CTableLogInfo.TableName = CTable.Name
CTable.ApplCTableLogInfo)
Next